πŸ”— Python Tutorial β€” Itertools Module

Introduction 🌟

The itertools module provides powerful tools for working with iterators. It helps you loop efficiently, generate combinations, create infinite iterators, and build complex iteration logic.

Note

πŸ’‘ itertools = β€œIterator Tools”
πŸ’‘ Highly optimized β†’ super fast
πŸ’‘ Used in algorithms, data processing, AI, simulations, and combinatorics

1. Importing itertools 🧱

import_itertools.py

import itertools

2. Infinite Iterators ♾️

count() β€” Infinite Counting

count_example.py

for num in itertools.count(start=10, step=2):
    print(num)
    if num > 20:
        break

βœ” Generates: 10, 12, 14, ...

cycle() β€” Repeat a Sequence Forever

cycle_example.py

for item in itertools.cycle(["A", "B", "C"]):
    print(item)
    break

βœ” Cycles through values infinitely

repeat() β€” Repeat a Value

repeat_example.py

for x in itertools.repeat("Hi", 3):
    print(x)

βœ” Useful for filling data

3. Combinatoric Iterators 🎯

product() β€” Cartesian Product

product_example.py

for p in itertools.product([1, 2], ["A", "B"]):
    print(p)

βœ” Output: (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')

permutations()

permutations_example.py

for p in itertools.permutations([1, 2, 3], 2):
    print(p)

βœ” Order matters β†’ (1,2), (2,1)…

combinations()

combinations_example.py

for c in itertools.combinations([1, 2, 3], 2):
    print(c)

βœ” Order doesn't matter β†’ (1,2), (1,3), (2,3)

combinations_with_replacement()

cwr_example.py

for c in itertools.combinations_with_replacement([1, 2], 2):
    print(c)

βœ” Ex: (1,1), (1,2), (2,2)

4. Utility Iterators 🧰

accumulate() β€” Running Totals

accumulate_example.py

import itertools, operator

nums = [1, 2, 3, 4]
print(list(itertools.accumulate(nums)))
print(list(itertools.accumulate(nums, operator.mul)))

βœ” Default: sum
βœ” With operator.mul β†’ running product

chain() β€” Join Iterables

chain_example.py

for item in itertools.chain([1, 2], ["A", "B"]):
    print(item)

βœ” Merges multiple iterables

chain.from_iterable()

chain_from_iterable.py

nested = [[1, 2], [3, 4]]
print(list(itertools.chain.from_iterable(nested)))

compress() β€” Filter by Selector

compress_example.py

items = ["A", "B", "C", "D"]
selectors = [1, 0, 1, 0]

print(list(itertools.compress(items, selectors)))

βœ” Output: ["A", "C"]

dropwhile() & takewhile()

drop_take_while.py

nums = [1, 2, 3, 4, 1]

print(list(itertools.dropwhile(lambda x: x < 3, nums)))
print(list(itertools.takewhile(lambda x: x < 3, nums)))

βœ” dropwhile β†’ skip until condition false
βœ” takewhile β†’ take while condition true

filterfalse()

filterfalse_example.py

print(list(itertools.filterfalse(lambda x: x % 2 == 0, [1,2,3,4])))

βœ” Opposite of filter()

5. Grouping Data β€” groupby() πŸ“Š

groupby_example.py

data = [("A", 1), ("A", 2), ("B", 1), ("B", 3)]

for key, group in itertools.groupby(data, lambda x: x[0]):
    print(key, list(group))

Note

πŸ’‘ groupby requires data to be sorted by the key

6. Real-World Example β€” Password Generator πŸ”

password_itertools.py

import itertools, string

chars = string.ascii_letters + string.digits
passwords = itertools.product(chars, repeat=3)

for pwd in passwords:
    print("".join(pwd))
    break

βœ” Generates password combinations

7. Real-World Example β€” Flatten Nested Lists πŸ“₯

flatten_example.py

nested = [[1, 2], [3, 4, 5]]
flat = list(itertools.chain.from_iterable(nested))
print(flat)

8. Itertools Cheat Sheet πŸ“˜

CategoryFunctions
Infinite Iteratorscount, cycle, repeat
Combinatoricsproduct, permutations, combinations
Filteringcompress, dropwhile, takewhile, filterfalse
Joiningchain, chain.from_iterable
Accumulationaccumulate
Groupinggroupby

Best Practices πŸ’‘

  • βœ” Use product, combinations for combinatorics
  • βœ” Use infinite iterators carefully β†’ always add a break
  • βœ” Prefer chain for merging lists instead of β€œ+”
  • βœ” Use groupby after sorting data
  • βœ” itertools works best with generators β†’ memory efficient

Conclusion πŸŽ‰

>>β€œitertools transforms simple loops into elegant, powerful, high-performance iteration pipelines.” ✨

You now fully understand the itertools module! Want the next topic? Try Functools, Statistics, Shutil, or Pathlib. Just tell me! 😊