819 words
4 minutes
itertools.count()

I. itertools.count()#

`itertools.count()` (计数迭代器) creates an infinite iterator (无限迭代器) that generates evenly spaced numbers(等间距数字) starting from a specified value.

1. Basic Usage#

`itertools.count()` (计数迭代器) generates an infinite arithmetic progression. Use it when you need an endless sequence of numbers for generating IDs, indices, or combining with other iterators. Warning: Always provide a termination condition when iterating over count() to avoid infinite loops.

1) Function Parameters#

`itertools.count(start=0, step=1)` (起始值, 步长) accepts two numeric parameters. `start` (起始值) defines the first value in the sequence, while `step` (步长) determines the increment between consecutive values. Both parameters can be integers, floats, or any numeric type that supports addition.
import itertools
# Default: start=0, step=1
counter = itertools.count()
print(next(counter)) # 0
print(next(counter)) # 1
# Custom start and step
counter = itertools.count(start=5, step=3)
print(next(counter)) # 5
print(next(counter)) # 8
print(next(counter)) # 11
# Using float step
counter = itertools.count(start=1.0, step=0.5)
print([next(counter) for _ in range(3)]) # [1.0, 1.5, 2.0]
Note: Using floating-point steps may lead to precision accumulation errors over many iterations. Consider using integers and dividing when precise decimal values are needed.

2. Practical Applications#

`itertools.count()` (计数迭代器) shines in scenarios requiring automatic indexing or sequence generation. Common use cases include adding line numbers to data, generating unique IDs, and creating paginated sequences. Its infinite nature makes it particularly useful when the iteration length is determined by another iterable.

1) Adding Indices to Data#

Combine `count()` with `zip()` to automatically number items (自动编号项目) in any iterable. This pattern is memory-efficient because it generates indices on-the-fly rather than storing them in a list.
import itertools
# Adding line numbers to text lines
lines = ["First line", "Second line", "Third line"]
numbered_lines = zip(itertools.count(1), lines)
for num, line in numbered_lines:
print(f"{num}: {line}")
# Output:
# 1: First line
# 2: Second line
# 3: Third line
# Creating dictionary with auto-generated keys
names = ["Alice", "Bob", "Charlie"]
user_dict = dict(zip(itertools.count(100), names))
print(user_dict) # {100: 'Alice', 101: 'Bob', 102: 'Charlie'}

2) Generating Infinite Sequences#

Use `count()` with `itertools.islice()` to generate finite slices of arithmetic sequences (生成有限段的算术序列). This approach is ideal for generating test data, mathematical sequences, or pagination where you need predictable, spaced values.
import itertools
# First 5 multiples of 10
multiples_of_10 = itertools.islice(itertools.count(10, 10), 5)
print(list(multiples_of_10)) # [10, 20, 30, 40, 50]
# Skip first 3, then take 4 numbers
skip_take = itertools.islice(itertools.count(100, -1), 3, 7)
print(list(skip_take)) # [97, 96, 95, 94]
# Generating powers of 2 using indices
powers_of_2 = (2 ** i for i in itertools.islice(itertools.count(), 6))
print(list(powers_of_2)) # [1, 2, 4, 8, 16, 32]
Pattern (模式)Code Example (代码示例)Use Case (使用场景)
1-based indexingzip(itertools.count(1), data)Displaying numbered lists, generating SQL IDs
Staggered stepsitertools.islice(itertools.count(0, 5), 10)Creating evenly spaced time intervals, pagination offsets
Descending sequencesitertools.islice(itertools.count(100, -1), 5)Generating countdowns, reverse numbering

3. Performance Comparison#

`itertools.count()` (计数迭代器) is implemented in C, making it significantly faster than manual Python counter loops (比手动Python计数循环快得多). Choose count() when you need infinite sequences or functional composition, and use `range()` for simple finite sequences.
import itertools
import time
# Manual counter (Python loop)
def manual_counter(n):
result = []
i = 0
while i < n:
result.append(i)
i += 1
return result
# Count with islice (C implementation)
def count_islice(n):
return list(itertools.islice(itertools.count(), n))
# Range (most optimized for finite sequences)
def range_approach(n):
return list(range(n))
# n = 10,000,000
# manual_counter: ~0.85s
# count_islice: ~0.42s
# range_approach: ~0.28s
Method (方法)Implementation (实现)Best For (最佳场景)Limitation (限制)
Manual counterPython loopSimple educational examplesSlow for large iterations
itertools.count()C implementationInfinite sequences, functional pipelinesRequires islice for finite use
enumerate()Built-in functionIndexing existing iterablesFixed start=0, no custom step
range()C implementationSimple finite sequencesCannot be infinite
💡 One-line Takeaway
`itertools.count()` is your go-to C-level tool for infinite arithmetic sequences — pair it with `zip()` for auto-indexing or `islice()` for finite slices, but never iterate directly without a termination condition.
itertools.count()
https://lxy-alexander.github.io/blog/posts/python/data_structures/itertoolscount/
Author
Alexander Lee
Published at
2026-03-20
License
CC BY-NC-SA 4.0