0Pricing
Python Academy · Lesson

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 18

count()

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 41

All lessons in this course

  1. itertools: Infinite and Finite Iterators
  2. itertools: Combinatorics
  3. functools: partial and reduce
  4. functools: lru_cache and cached_property
← Back to Python Academy