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
Using index element
Here, we are using an iterator variable to iterate through a list.
Python3
# create a list of subjectsdata = ["java", "python", "HTML", "PHP"]print("Indices in the list:")# display indices in the listfor i in range(len(data)): print(i)print("Index values in the list:")# display each index value in the listfor i in range(len(data)): print(data[i]) |
Output:
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.
Python
# create a list of subjectsdata = ["java", "python", "HTML", "PHP"]print("Indices and values in list:")# get the indices and values using enumerate methodfor i in enumerate(data): print(i) |
Output:
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.
Python3
# create a list of subjectsdata = ["java", "python", "HTML", "PHP"]print("Indices in list:")# get the indices using list comprehension methodprint([i for i in range(len(data))])print("values in list:")# get the values from indices using list# comprehension methodprint([data[i] for i in range(len(data))]) |
Output:
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
Python3
# create a index list that stores listindexlist = [0, 1, 2, 3]# create a list of subjectsdata = ["java", "python", "HTML", "PHP"]print("index and values in list:")# get the values from indices using zip methodfor index, value in zip(indexlist, data): print(index, value) |
Output:
index and values in list: 0 java 1 python 2 HTML 3 PHP



