Stop Using range() in Your Python for Loops

How to access the current index using the enumerate() function

Photo by bantersnaps on Unsplash

The 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.

If you’re coming from other popular languages such as PHP or JavaScript, you’re familiar with using a variable to keep track of your current index.

// JavaScript Example
let scores = [54,67,48,99,27];
for(const i=0; i < scores.length; i++) {
   console.log(i, scores[i]);
0 54
1 67
2 48
3 99
4 27

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

The traditional 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.

In fact, even in JavaScript there are methods of directly iterating over arrays (forEach() and for…of).

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 1 to 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!

Published by Ahmed's

Hello, I’m Ahmed, Crew trainer for Zohr gas field. I am a software engineer, consultant, and Adobe, Autodesk, Microsoft instructor/tutor. Currently living in Dumyat al Jadidah, Damietta, Egypt. My interests range from education to technology. I am also interested in entrepreneurship, programming, and cooking. I'm a member of the Scientific Research Center at the US Embassy.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create your website with
Get started
%d bloggers like this: