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')]
>>> list(enumerate(iter('word')))
[(0, 'w'), (1, 'o'), (2, 'r'), (3, 'd')]

Both will emit a sequence of numbers of two tuples. The first item in each tuple is an integer counter. The second item comes from the iterator. In this example, the iterator is built from a string of characters.

The zip() function is made slightly simpler with the use of the count() function, as shown in the following command:

zip(count(1,3), some_iterator)

The value of count(b, s) is the sequence of values . In this example, it will provide values of 1, 4, 7, 10, and so on as the identifiers for each value from the enumerator. A sequence such as this is a challenge with the enumerate() function because it doesn't provide a way to change the step. Here's how this can be done with the enumerate() function:

((1+3*e, x) for e,x in enumerate(some_iterator))
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset