Python Gem #15: itertools.count

The Problem

Adam Marshall
1 min readSep 14, 2017

You need to iterate over an infinite series of numbers, breaking when a condition is met.

Current Solution

n = 0
results = []
while True:
if <condition>:
break

results.append(<element>)
n += 1

Better Solution

import itertoolsresults = []
for x in itertools.count():
if <condition>:
break
results.append(<element>)

itertools.count is an iterator of evenly spaced values, starting at n, and progressing by step. These values default to 0 and 1 respectively.

itertools.count() # => 0, 1, 2, 3, 4, 5....
itertools.count(1) # => 1, 2, 3, 4, 5, 6...
itertools.count(1, 3) # => 1, 4, 7, 10, 13...

This is a daily series called Python Gems. Each short posts covers a detail, feature or application of the python language that you can use to increase your codes readability while decreasing its length.

P.S I’m trying out a more structured format that gets to the code and issue at hand faster. I think it works better then my previous ramblings. Tell me what you think 😄

--

--