Accessing index and value in Python list

Last Updated : 09 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list, and our task is to access both the index and value of each element in the list using Python. For example, using enumerate(list) in a loop like for index, value in enumerate(list) allows us to access both the index and the value together.

Using enumerate()

enumerate() is preferred and most efficient method for accessing both index and value in Python. It doesn't require manual handling of indices.

Python
a = [1, 4, 5, 6, 7]

for i, v in enumerate(a):
    print(i, v)

Output
0 1
1 4
2 5
3 6
4 7

Explanation: This code uses enumerate() to loop through the list a, where i represents the index and v represents the value at that index. It prints each index-value pair in the list.

Using zip()

zip() can be used while working with two or more list (or any iterable) and need to combine their elements along with their indices. You can also create a custom index range to pair with list values.

Python
a = [1, 4, 5, 6, 7]
b = ['a', 'b', 'c', 'd', 'e']

for i, v in zip(range(len(a)), zip(a,b)):
    print(i, v)

Output
0 (1, 'a')
1 (4, 'b')
2 (5, 'c')
3 (6, 'd')
4 (7, 'e')

Explanation: This code uses zip() to pair elements from lists a and b, and then combines it with range(len(a)) to include the index. In each iteration, i is the index, and v is a tuple containing the corresponding elements from a and b. It prints the index and the paired values.

Using list comprehension

List comprehensions provide a Pythonic way to create a new list, with index value pair. It can be used when you need to store the results in a new list.

Python
a = [1, 4, 5, 6, 7]

print([(i, a[i]) for i in range(len(a))])

Output
[(0, 1), (1, 4), (2, 5), (3, 6), (4, 7)]

Explanation: This code uses a list comprehension to create a list of tuples, where each tuple contains the index i and the corresponding value a[i] from the list a. It then prints the list of index-value pairs.

Related Articles:


Next Article

Similar Reads