Enumeration
Sometimes, you want to keep the record of the iteration you're at while using an iterable. A naive approach would be to get the length of the iterable, use the range function, and then use each number to get values from the iterable—indeed, that is how loops work in other languages, such as Java and JavaScript. But don't do that! Indeed, this construct requires two function calls in its basic case, and more if we need to numerate iterations, starting from a number other than zero. In Python, there is a better solution! Just use enumerate—this will create a generator that will return an index and a corresponding value from the original iterable, as a tuple. This can be used even if you had tuples already—just use parentheses for ...
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.
Read now
Unlock full access