How to Use Python’s Enumerate Function to Elegantly Access Index Variable in Python
The aim of this page📝is to cover the enumerate built-in function which enables a more pythonic use of the classical i
variable from a classical for loop.
1 min readNov 21, 2022
- E.g. javascript's
for(let i=0, i<list.length, i++) {<CODE>}
The enumerate constructor iterates over a collection and returns a series of pairs (tuple of 2)
- the first position being is the index
- the second position being is the value
The simplest example visualizes the tuple structure returned by enumerate()
>>> r = range(0, 18, 3)
>>> enumerate(r)
<enumerate object at 0x0354E948>
>>> r
range(0, 18, 3)
>>> for range_item in enumerate(r): print(range_item)
...
(0, 0)
(1, 3)
(2, 6)
(3, 9)
(4, 12)
(5, 15)
3. Of course, it is more pythonic to use tuple unpacking to avoid directly dealing with the tuple indexing, etc.
- cool for having the index variable at hand without the need for its separate declaration