DEV Community

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

Posted on • Edited on

itertools in Python (2)

Buy Me a Coffee

*Memo:


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:

*Memo:

  • The 1st argument is iterable(Required-Type:Iterable).
  • The 2nd argument is func(Optional-Default:None-Type:Callable or NoneType):
  • The 3rd argument is initial(Optional-Default:None-Type:Any or NoneType):
    • It's the 1st element.
from itertools import accumulate

v = accumulate(iterable=[])
v = accumulate(iterable=[], func=None, initial=None)

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=lambda a, b: a+b)
v = accumulate(iterable=[1, 2, 3, 4, 5], func=add)
v = accumulate(iterable=[2, 3, 4, 5], initial=1)
v = accumulate(iterable=[2, 3, 4, 5], func=lambda a, b: a+b, 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=lambda a, b: a*b):
# for x in accumulate([1, 2, 3, 4, 5], func=mul):
    print(x)
# 1
# 2
# 6
# 24
# 120
Enter fullscreen mode Exit fullscreen mode
from itertools import accumulate
from operator import mul

for x in accumulate([1, 2, 3, 4, 5], func=lambda a, b: a*b, initial=10):
# for x in accumulate([1, 2, 3, 4, 5], func=mul, initial=10):
    print(x)
# 10
# 10
# 20
# 60
# 240
# 1200
Enter fullscreen mode Exit fullscreen mode

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

*Memo:

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

v = batched(iterable='', n=1)
v = batched(iterable='', n=1, strict=False)
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='ABCDEFGHIJ', n=4)
v = batched(iterable=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], n=4)

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

v = batched(iterable='ABCDEFGHIJ', n=4, strict=True)
v = batched(iterable=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], n=4,
            strict=True)

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

for x in batched(iterable='ABCDEFGHIJ', n=4):
# for x in batched(iterable=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
#                  n=4):
    print(x)
# ('A', 'B', 'C', 'D')
# ('E', 'F', 'G', 'H')
# ('I', 'J')
Enter fullscreen mode Exit fullscreen mode
from itertools import batched

for x in batched(iterable='ABCDEFGHIJ', n=4, strict=True):
# for x in batched(iterable=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
#                  n=4, strict=True):
    print(x)
# ('A', 'B', 'C', 'D')
# ('E', 'F', 'G', 'H')
# ValueError: batched(): incomplete batch
Enter fullscreen mode Exit fullscreen mode

chain() and chain.from_iterable() can return the iterator which returns the elements of chained *iterables and iterable respectively one by one as shown below:

*Memo for chain():

  • The 1st arguments are *iterables(Optional-Default:()-Type:Iterable):
    • Don't use any keywords like *iterables=, iterables=, etc.

*Memo for chain.from_iterable():

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

v = chain()
v = 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('ABCDEF')
v = chain('ABC', 'DE', 'F')
v = chain(['A', 'B', 'C', 'D', 'E', '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
from itertools import chain

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

Top comments (0)