Stop Using range() in Your Python for Loops

Stop Using range() in Your Python for Loops

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

Image for postPhoto 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.

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.

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!

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!

23