How to Get Index in Python For Loop

Python’s for loop is a powerful tool that allows you to iterate over sequences such as lists, tuples, strings, and other iterable objects. When working with lists or other iterables, you often need to access the index of the current element in addition to the element itself. 

To get the index along with the element, you can use the enumerate() function in combination with the for loop. The enumerate() function adds a counter to an iterable, returning an enumerate object. Each item in the enumerate object is a tuple containing a count (the index) and the value from the iterable.

syntax:

for index, element in enumerate(iterable):
  # do something with index and element

Example 1

Printing elements with their indices.

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
  print(f"{index}: {fruit}")

Output:

0: apple
1: banana
2: cherry

Example 2

Finding the index of a specific element.

colors = ["red", "green", "blue", "yellow", "red"]
target_color = "red"
for index, color in enumerate(colors):
  if color == target_color:
    print(f"Index of {target_color} is {index}
python for loop get index

Example 3

Creating a dictionary from two lists.

keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
dictionary = dict()
for index, key in enumerate(keys):
  dictionary[key] = values[index]
print(dictionary)

Output:

{'name': 'Alice', 'age': 25, 'city': 'New York'}