How to Use itertools in Python: Syntax and Examples
Use the
itertools module in Python by importing it and then calling its functions like count(), cycle(), or combinations() to create efficient iterators. These functions help you loop over data in powerful ways without extra memory use.Syntax
First, import the itertools module. Then use its functions by calling itertools.function_name(arguments). Each function returns an iterator that you can loop over or convert to a list.
- import itertools: Loads the module.
- itertools.count(start, step): Creates an infinite counter starting at
start. - itertools.cycle(iterable): Repeats elements of
iterableendlessly. - itertools.combinations(iterable, r): Generates all
r-length combinations fromiterable.
python
import itertools # Example syntax calls counter = itertools.count(10, 2) # counts 10, 12, 14... cycler = itertools.cycle(['A', 'B', 'C']) # repeats A, B, C endlessly combos = itertools.combinations([1, 2, 3], 2) # pairs of elements
Example
This example shows how to use itertools.count() to generate numbers, itertools.cycle() to repeat letters, and itertools.combinations() to get pairs from a list.
python
import itertools # Count from 5 by 3s, stop after 5 numbers counter = itertools.count(5, 3) print('Count:') for _ in range(5): print(next(counter)) # Cycle through letters A, B, C, stop after 6 prints cycler = itertools.cycle(['A', 'B', 'C']) print('\nCycle:') for _ in range(6): print(next(cycler)) # Combinations of 2 from list combos = itertools.combinations([1, 2, 3], 2) print('\nCombinations:') for combo in combos: print(combo)
Output
Count:
5
8
11
14
17
Cycle:
A
B
C
A
B
C
Combinations:
(1, 2)
(1, 3)
(2, 3)
Common Pitfalls
Common mistakes include:
- Using infinite iterators like
count()orcycle()without a stopping condition, causing your program to run forever. - Forgetting to import
itertoolsbefore using its functions. - Trying to print an iterator directly instead of looping or converting it to a list.
python
import itertools # Wrong: infinite loop without stop # for i in itertools.count(1): # print(i) # This runs forever # Right: limit the loop for i in itertools.islice(itertools.count(1), 5): print(i) # Prints 1 to 5
Output
1
2
3
4
5
Quick Reference
| Function | Description |
|---|---|
| count(start=0, step=1) | Infinite counter starting at start, increasing by step |
| cycle(iterable) | Repeats elements of iterable endlessly |
| repeat(object, times=None) | Repeats object times times (infinite if times is None) |
| combinations(iterable, r) | All r-length combinations of elements |
| permutations(iterable, r=None) | All r-length permutations of elements |
| islice(iterable, stop) | Slice iterator to stop after given elements |
| chain(*iterables) | Combine multiple iterables into one |
| compress(data, selectors) | Filters data elements where selectors are True |
Key Takeaways
Import itertools to access powerful iterator functions for efficient looping.
Use functions like count, cycle, and combinations to create infinite or finite iterators.
Always control infinite iterators with limits to avoid endless loops.
Itertools functions return iterators; convert to list or loop to see results.
Refer to itertools documentation for many useful iterator tools beyond basics.