Accessing index and value in Python list
There are various methods to access the elements of a list, but sometimes we may require to access an element along with the index on which it is found. Let’s see all the different ways of accessing both index and value in a list.
Accessing index and value in list 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.
a = [1, 4, 5, 6, 7]
# get index and value using enumerate
for index, value in enumerate(a):
print(index, value)
# pass custom starting index by passing start parameter
# for index, value in enumerate(a, start=2):
Output
0 1 1 4 2 5 3 6 4 7
enumerate() creates an enumerate
object which can be directly iterated over in a for loop, to get both index and value of each item in a single step.
Accessing index and value in 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.
a = [1, 4, 5, 6, 7]
b = ['a', 'b', 'c', 'd', 'e']
# using zip() to get index and value
for index, value in zip(range(len(a)), zip(a,b)):
print(index, value)
Output
0 (1, 'a') 1 (4, 'b') 2 (5, 'c') 3 (6, 'd') 4 (7, 'e')
With zip(), we are using range(len(values))
to
generate indices to pair with combined elements of the lists.
Note: Using enumerate() should preferred over zip() while working with single iterable, as enumerate directly works on iterable, whereas zip() has the overhead of creating tuples by combining multiple iterables.
Accessing index and value in list 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.
a = [1, 4, 5, 6, 7]
# using list comprehension to
# get index and value
print([(i, a[i]) for i in range(len(a))])
Output
[(0, 1), (1, 4), (2, 5), (3, 6), (4, 7)]