DEV Community

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

Posted on • Edited on

itertools in Python (2)

Buy Me a Coffee

*Memo:

cycle() can return the iterator which endlessly repeats the 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 cycle

v = cycle('')
v = cycle([])

print(v)
# <itertools.cycle object at 0x0000027EC02BBB40>

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

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

print(next(v)) # A
print(next(v)) # B
print(next(v)) # C
print(next(v)) # A
print(next(v)) # B
print(next(v)) # C
print(next(v)) # A
print(next(v)) # B
Enter fullscreen mode Exit fullscreen mode
from itertools import cycle

count = 0

for x in cycle('ABC'):
# for x in cycle(['A', 'B', 'C']):
    if count == 8:
        break
    print(x)
    count += 1
# A
# B
# C
# A
# B
# C
# A
# B
Enter fullscreen mode Exit fullscreen mode

repeat() can return the iterator which endlessly or limitedly repeats object as shown below:

*Memo:

  • The 1st argument is object(Required-Type:Any).
  • The 2nd argument is times(Optional-Type:int):
    • If it's not set, the iterator is endlessly repeated otherwise limitedly repeated.
from itertools import repeat

v = repeat(object='Hello')

print(v)
# repeat('Hello')

print(type(v))
# <class 'itertools.repeat'>

print(next(v)) # Hello
print(next(v)) # Hello
print(next(v)) # Hello
print(next(v)) # Hello
print(next(v)) # Hello
Enter fullscreen mode Exit fullscreen mode
from itertools import repeat

v = repeat(object='Hello', times=3)

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

for x in repeat(object='Hello', times=3):
    print(x)
# Hello
# Hello
# Hello
Enter fullscreen mode Exit fullscreen mode
from itertools import repeat

v = repeat(object=['H', 'e', 'l', 'l', 'o'])

print(v)
# repeat(['H', 'e', 'l', 'l', 'o'])

print(next(v)) # ['H', 'e', 'l', 'l', 'o']
print(next(v)) # ['H', 'e', 'l', 'l', 'o']
print(next(v)) # ['H', 'e', 'l', 'l', 'o']
print(next(v)) # ['H', 'e', 'l', 'l', 'o']
print(next(v)) # ['H', 'e', 'l', 'l', 'o']
Enter fullscreen mode Exit fullscreen mode
from itertools import repeat

v = repeat(object=['H', 'e', 'l', 'l', 'o'], times=3)

print(next(v)) # ['H', 'e', 'l', 'l', 'o']
print(next(v)) # ['H', 'e', 'l', 'l', 'o']
print(next(v)) # ['H', 'e', 'l', 'l', 'o']
print(next(v)) # StopIteration:
Enter fullscreen mode Exit fullscreen mode
from itertools import repeat

for x in repeat(object=['H', 'e', 'l', 'l', 'o'], times=3):
    print(x)
# ['H', 'e', 'l', 'l', 'o']
# ['H', 'e', 'l', 'l', 'o']
# ['H', 'e', 'l', 'l', 'o']
Enter fullscreen mode Exit fullscreen mode

Top comments (0)