Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to Access Index in Python’s for Loop

  • Last Updated : 23 Sep, 2021

In this article, we will discuss accessing Index in Python for a loop.

We can access the index by using:

  1. Using index element
  2. Using enumerate()
  3. Using List Comprehensions
  4. 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.



Python3




# create a list of subjects
data = ["java", "python", "HTML", "PHP"]
  
print("Indices in the list:")
  
  
# display indices in the list
for i in range(len(data)):
    print(i)
  
print("Index values in the list:")
# display each index value in the list
for 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 subjects
data = ["java", "python", "HTML", "PHP"]
  
  
print("Indices and values in list:")
  
# get the indices and values using enumerate method
for 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 subjects
data = ["java", "python", "HTML", "PHP"]
  
print("Indices in list:")
  
# get the indices  using list comphrension method
print([i for i in range(len(data))])
  
print("values in list:")
  
# get the values from indices  using list 
# comphrension method
print([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 list
indexlist = [0, 1, 2, 3]
  
# create a list of subjects
data = ["java", "python", "HTML", "PHP"]
  
  
print("index and values in list:")
  
# get the values from indices  using zip method
for index, value in zip(indexlist, data):
    print(index, value)

Output:

index and values in list:
0 java
1 python
2 HTML
3 PHP



My Personal Notes arrow_drop_up
Recommended Articles
Page :