Get the Index While Looping with Enumerate

174次阅读
没有评论

Yesterday we saw how to create lists efficiently with list comprehensions. Today, let’s look at another common looping scenario: needing to access both the item and its index within a list.

A programmer coming from another language might approach this by creating a counter variable and manually incrementing it inside the loop.

Python

# The manual counter way
my_list = ['apple', 'banana', 'cherry']
index = 0
for fruit in my_list:
  print(f"Index: {index}, Fruit: {fruit}")
  index += 1

This works, but it’s not ideal. It requires managing an extra variable (index), making the code more cluttered and prone to errors (e.g., forgetting to increment the counter). Python provides a much cleaner and safer way to handle this.

The Pythonic Way: enumerate()

The built-in enumerate() function is the perfect tool for this job. It takes any iterable (like a list) and returns a special enumerate object, which yields pairs of (index, item) as you loop through it.

Python

# The Pythonic way with enumerate
my_list = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(my_list):
  print(f"Index: {index}, Fruit: {fruit}")

How does it work?

The enumerate() function wraps around your list and, in each step of the loop, gives you both the position and the value. You can then unpack this pair directly into two variables, index and fruit. The resulting code is more concise and easier to read, as the intent is perfectly clear.

Bonus Tip:

By default, enumerate starts counting from index 0. If you need to start counting from a different number, like 1, you can pass a second argument start:

Python

for index, fruit in enumerate(my_list, start=1):
  print(f"Item #{index}: {fruit}")

# Output:
# Item #1: apple
# Item #2: banana
# Item #3: cherry

Using enumerate() is a standard practice in Python for creating clean, readable loops that need access to an index. We’ll be back with another tip tomorrow!

正文完
 0
评论(没有评论)
验证码