Home »
Python
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?
Submitted by Sapna Deraje Radhakrishna, on October 25, 2019
Using range of length
Using the range function along with the len() on a list or any collection will give access to the index of each item in the collection. One such example is below,
-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> list_of_cities = ['bangalore', 'delhi', 'mumbai', 'pune', 'chennai', 'vizag']
>>> 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
Using enumerate
Enumerate is also one such function that provides an option to read the index of the collection. Enumerate is a more idiomatic way to accomplish this task,
-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> list_of_cities = ['bangalore', 'delhi', 'mumbai', 'pune', 'chennai', 'vizag']
>>> 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.
TOP Interview Coding Problems/Challenges