Counting with count()

The built-in range() function is defined by an upper limit: the lower limit and step values are optional. The count() function, on the other hand, has a start and optional step, but no upper limit.

This function can be thought of as the primitive basis for a function such as enumerate(). We can define the enumerate() function in terms of zip() and count() functions, as follows:

enumerate = lambda x, start=0: zip(count(start), x)

The enumerate() function behaves as if it's a zip() function that uses the count() function to generate the values associated with some iterator.

Consequently, the following two commands are equivalent to each other:

>>> list(zip(count(), iter('word')))[(0, 'w'), (1, 'o'), (2, 'r'), (3, 'd')] ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.