How to access the current index using the enumerate() function
for loop. It is a cornerstone of programming — a technique you learn as a novice and one that you’ll carry through the rest of your programming journey.
It’s critical to understand that these
for loops do not actually iterate over the array; they manually iterate via an expression that serves as a proxy for referencing each array value.
In the example above,
i has no explicit relation to
scores, it simply happens to coincide with each necessary index value.
The Old (Bad) Way
for loop as shown above does not exist in Python. However, if you’re like me, your first instinct is to find a way to recreate what you’re comfortable with.
As a result, you may have discovered the
range() function and come up with something like this.
scores = [54,67,48,99,27] for i in range(len(scores)): print(i, scores[i]) """ 0 54 1 67 2 48 3 99 4 27 """
The problem with this
for loop is that it isn’t very “Pythonic”. We’re not actually iterating over the list itself, but rather we’re using
i as a proxy index.
Using the enumerate() Function
If you want to properly keep track of the “index value” in a Python
for loop, the answer is to make use of the
enumerate() function, which will “count over” an iterable—yes, you can use it for other data types like strings, tuples, and dictionaries.
The function takes two arguments: the iterable and an optional starting count.
If a starting count is not passed, then it will default to
0. Then, the function will return tuples with each current count and respective value in the iterable.
scores = [54,67,48,99,27]for i, score in enumerate(scores): print(i, score)
This code is so much cleaner. We avoid dealing with list indices, iterate over the actual values, and explicitly see each value in the
for loop’s definition.
Here’s a bonus, have you ever wanted to print a numbered list but had to print
i + 1 since the first index is
0? Simply pass the value
enumerate() and watch the magic!
scores = [54,67,48,99,27] for i, score in enumerate(scores, 1): print(i, score) """ 1 54 2 67 3 48 4 99 5 27 """
I hope this tutorial was helpful. What other uses of the
enumerate() function have you found? Do you find the syntax easier to read than
range(len())? Share your thoughts and experiences below!