Accessing index and value in a Python list


When we use a Python list, will be required to access its elements at different positions. In this article we will see how to get the index of specific elements in a list.

With list.Index

The below program sources the index value of different elements in given list. We supply the value of the element as a parameter and the index function returns the index position of that element.

Example

 Live Demo

listA = [11, 45,27,8,43]
# Print index of '45'
print("Index of 45: ",listA.index(45))
listB = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
# Print index of 'Wed'
print("Index of Wed: ",listB.index('Wed'))

Output

Running the above code gives us the following result −

('Index of 45: ', 1)
('Index of Wed: ', 3)

With range and len

In the below program we loo through each element of the list and apply a list function inner for loop to get the index.

Example

 Live Demo

listA = [11, 45,27,8,43]
#Given list
print("Given list: ",listA)
# Print all index and values
print("Index and Values: ")
print ([list((i, listA[i])) for i in range(len(listA))])

Output

Running the above code gives us the following result −

Given list: [11, 45, 27, 8, 43]
Index and Values:
[[0, 11], [1, 45], [2, 27], [3, 8], [4, 43]]

With enumearate

The enumerate function itself gives track of the index position along with the value of the elements in a list. So when we apply enumerate function to a list it gives both index and value as output.

Example

 Live Demo

listA = [11, 45,27,8,43]
#Given list
print("Given list: ",listA)
# Print all index and values
print("Index and Values: ")
for index, value in enumerate(listA):
   print(index, value)

Output

Running the above code gives us the following result −

Given list: [11, 45, 27, 8, 43]
Index and Values:
0 11
1 45
2 27
3 8
4 43

Updated on: 09-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements