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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.