How to Use itertools.count in Python: Simple Guide
Use
itertools.count(start=0, step=1) to create an infinite iterator that returns numbers starting from start, increasing by step. It is useful for generating endless sequences or indexes in loops.Syntax
The itertools.count function creates an infinite iterator that generates numbers starting from start and increments by step each time.
- start: The first number to generate (default is 0).
- step: The amount to increase each time (default is 1).
python
import itertools counter = itertools.count(start=10, step=2)
Example
This example shows how to use itertools.count to print the first 5 numbers starting from 5, increasing by 3 each time.
python
import itertools counter = itertools.count(start=5, step=3) for _ in range(5): print(next(counter))
Output
5
8
11
14
17
Common Pitfalls
Because itertools.count creates an infinite iterator, forgetting to limit iteration can cause your program to run forever or crash.
Always use it with a break condition or limit the number of iterations.
python
import itertools # Wrong: This will run forever # for num in itertools.count(): # print(num) # Right: Limit iterations with a break counter = itertools.count() for num in counter: if num > 5: break print(num)
Output
0
1
2
3
4
5
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| start | Starting number of the count | 0 |
| step | Increment between numbers | 1 |
Key Takeaways
itertools.count creates an infinite sequence starting from a given number.
Always limit iteration to avoid infinite loops when using itertools.count.
You can customize the start and step values to fit your needs.
Use next() to get the next number from the count iterator.
itertools.count is useful for generating indexes or endless counters.