DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

itertools in Python (5)

Buy Me a Coffee

*Memo:


itertools has the functions to create iterators.

*more-itertools has more functions by installing with pip install more-itertools.


pairwise() can return the iterator which returns a successive overlapping tuple of the two elements of iterable one by one as shown below:

*Memo:

  • The 1st argument is iterable(Required-Type:Iterable):
    • Don't use iterable=.
from itertools import pairwise

v = pairwise('')
v = pairwise([])

print(v)
# <itertools.pairwise object at 0x0000026B3E697730>

print(next(v))
# StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import pairwise

v = pairwise('ABCD')
v = pairwise(['A', 'B', 'C', 'D'])

print(next(v)) # ('A', 'B')
print(next(v)) # ('B', 'C')
print(next(v)) # ('C', 'D')
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import pairwise

for x in pairwise('ABCD'):
# for x in pairwise(['A', 'B', 'C', 'D']):
    print(x)
# ('A', 'B')
# ('B', 'C')
# ('C', 'D')
Enter fullscreen mode Exit fullscreen mode

starmap() can return the iterator which does function with the elements of iterable one by one to returns the result one by one as shown below:

*Memo:

  • The 1st argument is function(Required-Type:Callable):
    • Don't use function=.
  • The 2nd argument is iterable(Required-Type:Iterable):
    • Don't use iterable=.
from itertools import starmap

x = starmap(lambda: None, [])

print(x)
# <itertools.starmap object at 0x000001BE9A289CF0>

print(next(x))
# StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import starmap
from operator import add

x = starmap(lambda a, b: a+b, [(2, 5), (3, 2), (10, 3)])
x = starmap(add, [(2, 5), (3, 2), (10, 3)])

print(next(x)) # 7
print(next(x)) # 5
print(next(x)) # 13
print(next(x)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import starmap
from operator import mul

for x in starmap(lambda a, b: a*b, [(2, 5), (3, 2), (10, 3)]):
# for x in starmap(mul, [(2, 5), (3, 2), (10, 3)]):
    print(x)
# 10
# 6
# 30
Enter fullscreen mode Exit fullscreen mode
from itertools import starmap

for x in starmap(lambda a, b: a**b, [(2, 5), (3, 2), (10, 3)]):
# for x in starmap(pow, [(2, 5), (3, 2), (10, 3)]):
    print(x)
# 32
# 9
# 1000
Enter fullscreen mode Exit fullscreen mode

tee() can return a tuple of the iterators which each return the elements of iterable one by one as shown below:

*Memo:

  • The 1st argument is iterable(Required-Type:Iterable):
    • Don't use iterable=.
  • The 2nd argument is n(Optional-Default:2-Type:int):
    • It's the number of iterators.
    • It must be 0 <= x.
    • Don't use n=.
from itertools import tee

v = tee('ABC')
v = tee('ABC', 2)
v = tee(['A', 'B', 'C'])

print(v)
# (<itertools._tee object at 0x000001BE99D6E3C0>,
#  <itertools._tee object at 0x000001BE99F85440>)

print(next(v[0])) # A
print(next(v[0])) # B
print(next(v[0])) # C
print(next(v[1])) # A
print(next(v[1])) # B
print(next(v[1])) # C

print(next(v[0])) # StopIteration:
print(next(v[1])) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import tee

for x in tee('ABC'):
# for x in tee(['A', 'B', 'C']):
    for y in x:
        print(y)
# A
# B
# C
# A
# B
# C
Enter fullscreen mode Exit fullscreen mode
from itertools import tee

for x in tee('ABC', 3):
# for x in tee(['A', 'B', 'C'], 3):
    for y in x:
        print(y)
# A
# B
# C
# A
# B
# C
# A
# B
# C
Enter fullscreen mode Exit fullscreen mode

zip_longest() can return the iterator which aggregates the elements of *iterables one by one to returns a tuple of one or more elements one by one as shown below:

*Memo:

  • The 1st arguments are *iterables(Optional-Default:()-Type:Iterable):
    • Don't use any keywords like *iterables=, iterables=, etc.
  • The 2nd argument is fillvalue(Optional-Default:None-Type:Any or NoneType):
    • It's the value to fill the zero or more missing elements of a returned tuple.
    • fillvalue= must be used.
from itertools import zip_longest

v = zip_longest()
v = zip_longest((), fillvalue=None)

print(v)
# <itertools.zip_longest object at 0x000001BE99F29FD0>

print(next(v))
# StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import zip_longest

v = zip_longest('ABC')
v = zip_longest(['A', 'B', 'C'])

print(next(v)) # ('A',)
print(next(v)) # ('B',)
print(next(v)) # ('C',)
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import zip_longest

v = zip_longest('ABC', 'vwxyz')
v = zip_longest(['A', 'B', 'C'], ['v', 'w', 'x', 'y', 'z'])

print(next(v)) # ('A', 'v')
print(next(v)) # ('B', 'w')
print(next(v)) # ('C', 'x')
print(next(v)) # (None, 'y')
print(next(v)) # (None, 'z')
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import zip_longest

v = zip_longest('ABC', 'vwxyz', fillvalue='Abscent')
v = zip_longest(['A', 'B', 'C'], ['v', 'w', 'x', 'y', 'z'],
                fillvalue='Abscent')

print(next(v)) # ('A', 'v')
print(next(v)) # ('B', 'w')
print(next(v)) # ('C', 'x')
print(next(v)) # ('Abscent', 'y')
print(next(v)) # ('Abscent', 'z')
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import zip_longest

for x in zip_longest('ABC', 'vwxyz', [10, 20], fillvalue='Abscent'):
# for x in zip_longest(['A', 'B', 'C'], ['v', 'w', 'x', 'y', 'z'],
#                      [10, 20], fillvalue='Abscent'):
    print(x)
# ('A', 'v', 10)
# ('B', 'w', 20)
# ('C', 'x', 'Abscent')
# ('Abscent', 'y', 'Abscent')
# ('Abscent', 'z', 'Abscent')
Enter fullscreen mode Exit fullscreen mode
from itertools import zip_longest

for x in zip_longest('ABC', 'vwxyz', [10, 20], fillvalue='Abscent'):
# for x in zip_longest(['A', 'B', 'C'], ['v', 'w', 'x', 'y', 'z'],
#                      [10, 20], fillvalue='Abscent'):
    for y in x:
        print(y)
# A
# v
# 10
# B
# w
# 20
# C
# x
# Abscent
# Abscent
# y
# Abscent
# Abscent
# z
# Abscent
Enter fullscreen mode Exit fullscreen mode

Top comments (0)