April 2019
Intermediate to advanced
646 pages
16h 48m
English
Another typical example of a Python idiom is the use of enumerate(). This built-in function provides a convenient way to get an index when a sequence is iterated inside of a loop. Consider the following piece of code as an example of tracking the element index without the enumerate() function:
>>> i = 0 >>> for element in ['one', 'two', 'three']: ... print(i, element) ... i += 1 ... 0 one 1 two 2 three
This can be replaced with the following code, which is shorter and definitely cleaner:
>>> for i, element in enumerate(['one', 'two', 'three']): ... print(i, element) ... 0 one 1 two 2 three
If you need to aggregate elements of multiple lists (or any other iterables) in the one-by-one fashion, you can use the built-in zip()