Getting the Index (Loop Count) in Python for Loops: How to Use the enumerate Function

Python’s for loops are very convenient because they let you process elements directly from a list. However, there are times when you need information like “which element number is this? (index)” or “how many times has the loop run?”.

Users coming from other languages often try to use range(len(list)), but this is not recommended in Python. Instead, using the built-in enumerate() function is the most efficient and readable method (the “Pythonic” way).

This article explains how to get both the index and the element simultaneously during a loop using the enumerate() function.


目次

1. Basic Usage with Lists

The enumerate() function takes an iterable (like a list) as an argument. It returns a pair of (index, element) for each iteration of the loop.

Syntax:

for index_variable, element_variable in enumerate(list):
    # Process

Example: Here is a program that displays a ranking list with the rank (index).

# Ranking data
ranking_list = ["Team-A", "Team-B", "Team-C", "Team-D"]

print("--- Tournament Results ---")

# 'idx' gets 0, 1, 2..., 'team' gets the list elements in order
for idx, team in enumerate(ranking_list):
    # Since index starts at 0, add 1 for display
    rank = idx + 1
    print(f"Rank {rank}: {team}")

Output:

--- Tournament Results ---
Rank 1: Team-A
Rank 2: Team-B
Rank 3: Team-C
Rank 4: Team-D

You no longer need to use range(len(ranking_list)) or access ranking_list[i], making the code much cleaner.

Changing the Start Index (start argument)

You can specify a start value as the second argument to enumerate(). This allows you to start the index count from a number other than 0. In the previous example, we calculated rank = idx + 1, but using start=1 makes that unnecessary.

# Specify start=1 to begin counting from 1
for rank, team in enumerate(ranking_list, start=1):
    print(f"Rank {rank}: {team}")

Output:

Rank 1: Team-A
Rank 2: Team-B
Rank 3: Team-C
Rank 4: Team-D

2. Usage with Dictionaries (dict)

enumerate() can also be used when looping through dictionaries. By combining it with the .items() method, you can handle the “Sequence Number,” “Key,” and “Value” all at once.

In this case, you need to be careful with variable unpacking. Since .items() returns a (key, value) tuple, you must structure your variables to match (index, (key, value)) returned by enumerate.

Syntax:

for index, (key, value) in enumerate(dictionary.items()):
    # Process

Example: A program that displays a product price list and assigns a product ID (sequence number) to each.

# Product and Price Dictionary
product_prices = {
    "Mouse": 2500,
    "Keyboard": 5000,
    "Monitor": 20000
}

print("--- Product List ---")

# Receive as idx, (name, price)
for idx, (name, price) in enumerate(product_prices.items(), start=1001):
    print(f"ID: {idx} | Product: {name} | Price: {price} yen")

Output:

--- Product List ---
ID: 1001 | Product: Mouse | Price: 2500 yen
ID: 1002 | Product: Keyboard | Price: 5000 yen
ID: 1003 | Product: Monitor | Price: 20000 yen

By keeping the parentheses around (name, price), you can cleanly unpack the contents of the tuple.


Summary

  • Use the enumerate() function when you need the index (position) during a loop.
  • You can get both the index and element simultaneously with for i, value in enumerate(list):.
  • Use the start argument to freely change the starting number of the index.
  • Combining it with dictionary .items() allows you to process dictionary elements with sequence numbers.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次