How to Access Index in Python’s for Loop
In this article, we will discuss accessing Index in Python for a loop.
We can access the index by using:
- Using index element
- Using enumerate()
- Using List Comprehensions
- Using zip()
Index element is used to represent the location of element in a list. Here we are accessing index through list of elements
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Using index element
Here, we are using an iterator variable to iterate through a list.
Indices in the list: 0 1 2 3 Index values in the list: java python HTML PHP
Using enumerate() method
This method is used in for loop which is used to get the index along with the corresponding element over the range.
Indices and values in list: (0, 'java') (1, 'python') (2, 'HTML') (3, 'PHP')
Using list comprehension method
This will make a list of index and then gives the index and index values.
Indices in list: [0, 1, 2, 3] values in list: ['java', 'python', 'HTML', 'PHP']
Using zip() method
Zip method is usedto zip the index and values at a time, we have to pass two lists one list is of index elements and another list is of elements
index and values in list: 0 java 1 python 2 HTML 3 PHP