Skip to Content
Expert Python Programming - Third Edition
book

Expert Python Programming - Third Edition

by Michał Jaworski, Tarek Ziadé, Cody Jackson
April 2019
Intermediate to advanced
646 pages
16h 48m
English
Packt Publishing
Content preview from Expert Python Programming - Third Edition

Other idioms

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()

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Expert Python Programming - Fourth Edition

Expert Python Programming - Fourth Edition

Michał Jaworski, Tarek Ziade, Tarek Ziadé

Publisher Resources

ISBN: 9781789808896Other