Home »
Python
Accessing the index in 'for' loops in Python
Last Updated : April 22, 2025
To access the index in Python's for loop, there are two approaches that you can use range of length and enumerate() method. Let's discuss them in detail.
1. Using Range of Length
Using the range() method along with the len() method on a list or any collection will give access to the index of each item in the collection. One such example is below,
Example
# A list of cities
list_of_cities = ["bangalore", "delhi", "mumbai", "pune", "chennai", "vizag"]
# Access Index in Python's for Loop using
# Range of Length
for i in range(len(list_of_cities)):
print("I like the city {}".format(list_of_cities[i]))
Output
I like the city bangalore
I like the city delhi
I like the city mumbai
I like the city pune
I like the city chennai
I like the city vizag
2. Using enumerate() Method
The enumerate() method is also one such metod that provides an option to read the index of the collection. The enumerate() is a more idiomatic way to accomplish this task,
Example
# A list of cities
list_of_cities = ["bangalore", "delhi", "mumbai", "pune", "chennai", "vizag"]
# Access Index in Python's for Loop using
# enumerate() Method
for num, name in enumerate(list_of_cities, start=1):
print(num, name)
Output
1 bangalore
2 delhi
3 mumbai
4 pune
5 chennai
6 vizag
Here in the above example, num refers to the index and name refers to the item in the given num index.
Python Accessing Index in 'for' Loops
Select the correct option to complete each statement about accessing the index in Python 'for' loops.
- To access the index of elements while using a for loop, we can use the ___ function.
- In a loop using enumerate, the first value returned by enumerate is the ___ of the item.
- To start the index from a number other than 0 while using enumerate, you can pass the ___ parameter.
Advertisement
Advertisement