DEV Community

Kelvin Wangonya
Kelvin Wangonya

Posted on • Originally published at wangonya.com on

10 2

When to use python's enumerate() instead of range() in loops

The range() function is often useful when iterating over a set of integers:

for n in range(50):
    ...

#

for n in range(10, 30):
    ...
Enter fullscreen mode Exit fullscreen mode

or a list of strings:

for fruit in ["apple", "mango", "banana"]:
    ...
Enter fullscreen mode Exit fullscreen mode

Now, say you want to iterate over the list of fruits and also show the index of the current item in the list. Using range(), this might be done like this:

fruits = ["apple", "mango", "banana"]

for i in range(len(fruits)):
    fruit = fruits[i]
    print(f"{i}: {fruit}")

# Output:
# 0: apple
# 1: mango
# 2: banana
Enter fullscreen mode Exit fullscreen mode

It gets the job done, but not very pythonic. You have to get the length of the list to keep track of the index, then index into the array to get the current fruit - which makes the code more verbose and harder to read.

A better way: enumerate()

fruits = ["apple", "mango", "banana"]

for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# Output:
# 0: apple
# 1: mango
# 2: banana
Enter fullscreen mode Exit fullscreen mode

Numbering can also be set to begin at any desired number.

fruits = ["apple", "mango", "banana"]

for i, fruit in enumerate(fruits, 7):
    print(f"{i}: {fruit}")

# Output
# 7: apple
# 8: mango
# 9: banana
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (1)

Collapse
 
bgatwitt profile image
bga

Cool. Thanks.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay