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

Postmark Image

20% off for developers shipping features, not fixing email

Build your product without worrying about email infrastructure. Our reliable delivery, detailed analytics, and developer-friendly API let you focus on shipping features that matter.

Start free

Top comments (1)

Collapse
 
bgatwitt profile image
bga

Cool. Thanks.

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️