Use enumerate Instead of range

in #python-dev • 4 days ago

Python Daily #001 — Use enumerate() Instead of range(len())

When looping through a list in Python, we sometimes need both the item and its index.

A common beginner approach is:

languages = ["Python", "JavaScript", "Go"]

for i in range(len(languages)):
    print(i, languages[i])

This works, but Python gives us a cleaner and more readable solution: enumerate().

languages = ["Python", "JavaScript", "Go"]

for index, language in enumerate(languages):
    print(index, language)

Output:

0 Python
1 JavaScript
2 Go

Starting the index from 1

By default, enumerate() starts counting from 0.

If you want the numbering to start from 1, simply use the start argument:

languages = ["Python", "JavaScript", "Go"]

for index, language in enumerate(languages, start=1):
    print(index, language)

Output:

1 Python
2 JavaScript
3 Go

Why is enumerate() better?

Compare these two approaches.

Using range(len())

for i in range(len(languages)):
    print(i, languages[i])

Using enumerate()

for i, language in enumerate(languages):
    print(i, language)

The second version is usually easier to read because you directly get both the index and the value.

It also avoids repeatedly accessing the list with:

languages[i]

A Practical Example

Suppose we want to print a simple numbered menu:

tools = ["Git", "Docker", "Python", "VS Code"]

for number, tool in enumerate(tools, start=1):
    print(f"{number}. {tool}")

Output:

1. Git
2. Docker
3. Python
4. VS Code

This pattern is useful for:

  • menus
  • numbered reports
  • processing rows of data
  • debugging
  • displaying search results
  • handling lists returned from APIs

Small Challenge

Given the following list:

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

Use enumerate() to produce:

Fruit 1: apple
Fruit 2: banana
Fruit 3: orange
Fruit 4: mango

Try solving it before looking at the answer.

Solution

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

for number, fruit in enumerate(fruits, start=1):
    print(f"Fruit {number}: {fruit}")

Python Tip of the Day

Before writing extra indexing logic, check whether Python already has a built-in function for the job.

Functions such as:

enumerate()
zip()
sorted()
sum()
any()
all()

can often make your code shorter, clearer, and easier to maintain.


That's today's Python tip.

I plan to share small Python examples and practical programming techniques regularly on this account.

Happy coding! 🐍

#python #programming #coding #tutorial #developer