DEV Community

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

Posted on

itertools in Python (2)

Buy Me a Coffee

*Memos:


itertools has the functions to create iterators.

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


accumulate() can return the iterator which accumulates the elements of iterable one by one to return the accumulated elements one by one as shown below:

*Memos:

  • The 1st argument is iterable(Required-Type:iterable).
  • The 2nd argument is func(Optional-Default:None-Type:callable). *It can be operator.
  • The 3rd argument is initial(Optional-Default:None-Type:object).
from itertools import accumulate

v = accumulate(iterable=[])

print(v)
# <itertools.accumulate object at 0x0000026906CF9850>

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

v = accumulate(iterable=[1, 2, 3, 4, 5])
v = accumulate(iterable=[1, 2, 3, 4, 5], func=None, initial=None)
v = accumulate(iterable=[1, 2, 3, 4, 5], func=add)
v = accumulate(iterable=[1, 2, 3, 4, 5], func=lambda a, b: a+b)
v = accumulate(iterable=[2, 3, 4, 5], initial=1)

print(next(v)) # 1
print(next(v)) # 3
print(next(v)) # 6
print(next(v)) # 10
print(next(v)) # 15
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import accumulate

for x in accumulate([1, 2, 3, 4, 5]):
    print(x)

print(next(v)) # 1
print(next(v)) # 3
print(next(v)) # 6
print(next(v)) # 10
print(next(v)) # 15
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import accumulate

for x in accumulate([1, 2, 3, 4, 5], initial=10):
# for x in accumulate([10, 1, 2, 3, 4, 5]):
    print(x)
# 10
# 11
# 13
# 16
# 20
# 25
Enter fullscreen mode Exit fullscreen mode
from itertools import accumulate
from operator import mul

for x in accumulate([1, 2, 3, 4, 5], func=mul):
# for x in accumulate([1, 2, 3, 4, 5], func=lambda a, b: a*b):
    print(x)
# 1
# 2
# 6
# 24
# 120
Enter fullscreen mode Exit fullscreen mode

batched() can return the iterator which batches the one or more elements of iterable one by one to return the batches one by one as shown below:

*Memos:

  • The 1st argument is iterable(Required-Type:iterable).
  • The 2nd argument is n(Required-Type:int). *It's the number of batches. *It must be 1 <= x.
  • The 3rd argument is strict(Optional-Default:False): *Memos:
    • If it's True, error occurs if the final batch is shorter than n.
    • strict= must be used.
from itertools import batched

v = batched(iterable='', n=1)
v = batched(iterable=[], n=1)

print(v)
# <itertools.batched object at 0x0000026905D0CE80>

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

v = batched(iterable='ABCDEFGH', n=3)
v = batched(iterable='ABCDEFGH', n=3, strict=False)
v = batched(iterable=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], n=3)

print(next(v)) # ('A', 'B', 'C')
print(next(v)) # ('D', 'E', 'F')
print(next(v)) # ('G', 'H')
Enter fullscreen mode Exit fullscreen mode
from itertools import batched

v = batched(iterable='ABCDEFGH', n=3, strict=True)

print(next(v)) # ('A', 'B', 'C')
print(next(v)) # ('D', 'E', 'F')
print(next(v)) # ValueError: batched(): incomplete batch
Enter fullscreen mode Exit fullscreen mode
from itertools import batched

for x in batched(iterable='ABCDEFGH', n=3):
    print(x)
# ('A', 'B', 'C')
# ('D', 'E', 'F')
# ('G', 'H')
Enter fullscreen mode Exit fullscreen mode
from itertools import batched

for x in batched(iterable='ABCDEFGH', n=3, strict=True):
    print(x)
# ('A', 'B', 'C')
# ('D', 'E', 'F')
# ValueError: batched(): incomplete batch
Enter fullscreen mode Exit fullscreen mode

You can use chain() and chain.from_iterable() as shown below:

*Memos:

  • chain() can return the iterator which chains *iterables to return the elements one by one: *Memos:
    • The 1st or the later arguments are *iterables(Optional-Type:iterable).
    • Don't use any keywords like *iterables=, iterables=, *iterable=, iterable=, etc.
  • chain.from_iterable() can return the iterator which returns the elements of iterable one by one: *Memos:
    • The 1st argument is iterable(Required-Type:iterable).
    • Don't use iterable=.
from itertools import chain

v = chain()
v = chain('')
v = chain([])
v = chain.from_iterable('')
v = chain.from_iterable([])

print(v)
# <itertools.chain object at 0x0000026906CEAD70>

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

v = chain('ABC')
v = chain(['A', 'B', 'C'])
v = chain.from_iterable('ABC')
v = chain.from_iterable(['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 chain

v = chain('ABC', 'DE')
v = chain(['A', 'B', 'C'], ['D', 'E'])
v = chain.from_iterable('ABCDE')
v = chain.from_iterable(['A', 'B', 'C', 'D', 'E'])

print(next(v)) # A
print(next(v)) # B
print(next(v)) # C
print(next(v)) # D
print(next(v)) # E
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import chain

v = chain('ABC', 'DE', 'F')
v = chain(['A', 'B', 'C'], ['D', 'E'], ['F'])
v = chain.from_iterable('ABCDEF')
v = chain.from_iterable(['A', 'B', 'C', 'D', 'E', 'F'])

print(next(v)) # A
print(next(v)) # B
print(next(v)) # C
print(next(v)) # D
print(next(v)) # E
print(next(v)) # F
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
for x in chain('ABC', 'DE', 'F'):
# for x in chain.from_iterable('ABCDEF'):
    print(x)
# A
# B
# C
# D
# E
# F
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.