← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Itertools

Topic: Functional Programming

Advertisement

Introduction

Itertools provides fast, memory-efficient tools for creating and working with iterators.

Infinite Iterators

import itertools

# Count (infinite counter)
counter = itertools.count(1, 2)  # 1, 3, 5, 7, ...
next(counter)  # 1

# Cycle (repeat infinitely)
cycle = itertools.cycle([1, 2, 3])  # 1, 2, 3, 1, 2, 3, ...

# Repeat
repeat = itertools.repeat("x", times=3)  # x, x, x

Finite Iterators

import itertools

# Accumulate (running totals)
acc = itertools.accumulate([1, 2, 3, 4])  # 1, 3, 6, 10

# Chain (combine iterables)
chained = list(itertools.chain([1, 2], [3, 4], [5, 6]))

# Compress (filter by selector)
compressed = list(itertools.compress("ABCDEF", [1, 0, 1, 0, 1, 0]))

# Drop/Take while
dropped = list(itertools.dropwhile(lambda x: x < 3, [1, 2, 3, 4, 1]))

Combinatoric Iterators

import itertools

# Permutations (order matters)
list(itertools.permutations([1, 2, 3], 2))  # (1,2), (1,3), (2,1), (2,3), (3,1), (3,2)

# Combinations (order doesn't matter)
list(itertools.combinations([1, 2, 3], 2))  # (1,2), (1,3), (2,3)

# Product (cartesian product)
list(itertools.product([1, 2], repeat=2))  # (1,1), (1,2), (2,1), (2,2)

Practice Problems

  1. Generate all possible PIN combinations
  2. Create running maximum iterator
  3. Group consecutive elements with groupby
  4. Find all anagrams using permutations
  5. Build infinite Fibonacci with cycle

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →