itertools: Infinite and Finite Iterators
Use count, cycle, islice, chain, and zip_longest.
What Is itertools?
itertools is a standard library module providing memory-efficient iterator building blocks. All functions return iterators, not lists.
import itertools
# count: infinite counter
for i in itertools.islice(itertools.count(10, 2), 5):
print(i, end=" ") # 10 12 14 16 18count()
count(start, step) produces an infinite arithmetic sequence. Always pair with islice or a break condition.
import itertools
for n in itertools.count(1, 10):
if n > 40:
break
print(n, end=" ") # 1 11 21 31 41All lessons in this course
- itertools: Infinite and Finite Iterators
- itertools: Combinatorics
- functools: partial and reduce
- functools: lru_cache and cached_property