Nearby lessons

121 of 159

Python - itertools Module

📌 What You Will Learn
  • Explain why itertools works well with iterators
  • Chain and repeat values with iterator helpers
  • Group consecutive values with groupby()
  • Generate combinations and permutations
  • Use zip_longest() for unequal iterables

Iterator building blocks

itertools contains composable tools that operate lazily. This helps process large or infinite streams without building unnecessary intermediate lists.

chain()

🐍Code Cell
1from itertools import chain
2 
3for item in chain([1, 2], ['a', 'b']):
4 print(item)
Output
1
2
a
b

count() and repeat()

count() produces an arithmetic progression and repeat() produces the same value repeatedly. Use islice() or a loop condition to bound consumption.

🐍Code Cell
1from itertools import count, islice, repeat
2 
3print(list(islice(count(10, 2), 3)))
4print(list(repeat('x', 3)))
Output
[10, 12, 14]
['x', 'x', 'x']

combinations() and permutations()

🐍Code Cell
1from itertools import combinations, permutations
2 
3print(list(combinations('ABC', 2)))
4print(list(permutations('AB', 2)))
Output
[('A', 'B'), ('A', 'C'), ('B', 'C')]
[('A', 'B'), ('B', 'A')]

groupby()

groupby() groups consecutive items by a key. Sort data first when equal keys are not already adjacent.

🐍Code Cell
1from itertools import groupby
2 
3for key, group in groupby('aaabbc'):
4 print(key, list(group))
Output
a ['a', 'a', 'a']
b ['b', 'b']
c ['c']

zip_longest()

🐍Code Cell
1from itertools import zip_longest
2 
3print(list(zip_longest([1, 2, 3], ['a'], fillvalue='-')))
Output
[(1, 'a'), (2, '-'), (3, '-')]

islice()

islice(iterable, start, stop, step) selects a bounded portion of an iterator without requiring random access.

Lazy evaluation and memory

Most itertools results are consumed once. Convert to list() only when you need all values stored at once, and be cautious with infinite iterators such as count().

📝 Key Takeaways
  • itertools functions generally return lazy iterators
  • chain() joins iterables without copying them first
  • combinations() and permutations() generate arrangement choices
  • groupby() groups consecutive equal keys
  • islice() and zip_longest() solve common iterator tasks

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8