Accessing the index in 'for' loops in Python

Accessing the index in 'for' loops: Here, we are going to learn how to access the index in 'for' loops in Python programming language? By Sapna Deraje Radhakrishna Last updated : December 18, 2023

Accessing Index in Python's for Loop

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 to Access Index in Python's for Loop using Range of Length

# 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 to Access Index in Python's for Loop using enumerate() Method

# 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 Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.