DEV Community

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

Posted on • Edited on

itertools in Python (4)

Buy Me a Coffee

*Memo:


itertools has the functions to create iterators.

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


groupby() can return the iterator which groups the elements of iterable by keys one by one to return a tuple of a key and the iterator of an element one by one as shown below:

*Memo:

  • The 1st argument is iterable(Required-Type:Iterable).
  • The 2nd argument is key(Optional-Default:None-Type:Callable or NoneType):
    • It's a key.
    • If it's None, each element of iterable is a key.
from itertools import groupby

v = groupby(iterable=[])
v = groupby(iterable=[], key=None)

print(v)
# <itertools.groupby object at 0x0000026906F60B20>

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

v = groupby(iterable=['AB', 'CDE', 'FG', 'H', 'IJK'])

print(next(v))
# ('AB', <itertools._grouper object at 0x0000027EC0549D80>)

print(next(v))
# ('CDE', <itertools._grouper object at 0x0000027EC0549D80>)

print(next(v))
# ('FG', <itertools._grouper object at 0x0000027EC0549D80>)

print(next(v))
# ('H', <itertools._grouper object at 0x0000027EC0549D80>)

print(next(v))
# ('IJK', <itertools._grouper object at 0x0000027EC0549D80>)

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

v = groupby(iterable=['AB', 'CDE', 'FG', 'H', 'IJK'])

key, x = next(v)
print(key, next(x))
# AB AB

key, x = next(v)
print(key, next(x))
# CDE CDE

key, x = next(v)
print(key, next(x))
# FG FG

key, x = next(v)
print(key, next(x))
# H H

key, x = next(v)
print(key, next(x))
# IJK IJK

key, x = next(v)
# StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import groupby

for key, x in groupby(iterable=['AB', 'CDE', 'FG', 'H', 'IJK']):
    print(key, next(x))
# AB AB
# CDE CDE
# FG FG
# H H
# IJK IJK
Enter fullscreen mode Exit fullscreen mode
from itertools import groupby

for key, x in groupby(iterable=['AB', 'CDE', 'FG', 'H', 'IJK'], key=len):
    print(key, next(x))
# 2 AB
# 3 CDE
# 2 FG
# 1 H
# 3 IJK
Enter fullscreen mode Exit fullscreen mode
from itertools import groupby

d = {}

for key, x in groupby(iterable=['AB', 'CDE', 'FG', 'H', 'IJK'], key=len):
    if not key in d:
        d.update({key:[]})
    d[key].append(next(x))

print(d)
# {2: ['AB', 'FG'], 3: ['CDE', 'IJK'], 1: ['H']}
Enter fullscreen mode Exit fullscreen mode
from itertools import groupby

for key, x in groupby(iterable='ABCDEFGHIJK'):
# for key, x in groupby(iterable=['A', 'B', 'C', 'D', 'E', 'F',
#                                 'G', 'H', 'I', 'J', 'K']):
    print(key, next(x))
# A A
# B B
# C C
# D D
# E E
# F F
# G G
# H H
# I I
# J J
# K K
Enter fullscreen mode Exit fullscreen mode
from itertools import groupby

for key, x in groupby(iterable='ABCDEFGHIJK', key=len):
# for key, x in groupby(iterable=['A', 'B', 'C', 'D', 'E', 'F',
#                                 'G', 'H', 'I', 'J', 'K'], key=len):
    print(key, next(x))
# 1 A
Enter fullscreen mode Exit fullscreen mode
from itertools import groupby

d = {}

for key, x in groupby(iterable='ABCDEFGHIJK', key=len):
# for key, x in groupby(iterable=['A', 'B', 'C', 'D', 'E', 'F',
#                                 'G', 'H', 'I', 'J', 'K'], key=len):
    if not key in d:
        d.update({key:[]})
    d[key].append(next(x))

print(d)
# {1: ['A']}
Enter fullscreen mode Exit fullscreen mode

islice() can return the iterator which returns the elements selected from iterable one by one between [start, end) as shown below:

*Memo:

  • The 1st argument is iterable(Required-Type:Iterable):
    • Don't use iterable=.
  • The 2nd argument is start or stop(Required-Type:int):
    • It's a start index(inclusive) or stop index(exclusive).
    • It must be 0 <= x.
    • If start is None, it's 0.
    • If stop is None, iterable is read to the end.
    • Don't use start= or stop=.
  • The 3rd argument is stop(Optional-Default:None-Type:int or NoneType):
    • It's a stop index(exclusive).
    • It must be 0 <= x.
    • If it's set and None, iterable is read to the end.
    • If it's not set and None, the 2nd argument stop is prioritized.
    • Don't use stop=.
  • The 4th argument is step(Optional-Default:None-Type:int or NoneType):
    • It's the interval of indices.
    • It must be 1 <= x.
    • If it's None, it's 1.
    • Don't use step=.
  • Only if two arguments are set, the 2nd argument is stop.
from itertools import islice

v = islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 9)
v = islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 20)
v = islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], None)
v = islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 0, 9)
v = islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 0, 20)
v = islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], None, None)
v = islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 0, 9, 1)
v = islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 0, 20, 1)
v = islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], None, None, None)

print(v)
# <itertools.islice object at 0x0000026906E7BD30>

print(next(v)) # -4
print(next(v)) # -3
print(next(v)) # -2
print(next(v)) # -1
print(next(v)) # 0
print(next(v)) # 1
print(next(v)) # 2
print(next(v)) # 3
print(next(v)) # 4
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import islice

v = islice([], 0)

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

for x in islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 4):
# for x in islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 0, 4):
# for x in islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 0, 4, 1):
    print(x)
# -4
# -3
# -2
# -1
Enter fullscreen mode Exit fullscreen mode
from itertools import islice

for x in islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 3, 7):
# for x in islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 3, 7, 1):
    print(x)
# -1
# 0
# 1
# 2
Enter fullscreen mode Exit fullscreen mode
from itertools import islice

for x in islice([-4, -3, -2, -1, 0, 1, 2, 3, 4], 1, 8, 2):
    print(x)
# -3
# -1
# 1
# 3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)