Play this article
enumerate
is a built-in function in Python that converts an iterable
to an indexed array. It's usually used when it's necessary to work with values and indexes while looping through a list.
first10Primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
for index, value in enumerate(first10Primes):
print(index, value)
'''
Output
0 2
1 3
2 5
3 7
4 11
5 13
6 17
7 19
8 23
9 29
'''
If you have some experience with Javascript, you'll notice a similarity in the array methods: forEach, map and filter.
const first10Primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
first10Primes.forEach((prime, index) => console.log(prime, index))
In Javascript's case, the index comes second.
In other data structures
enumerate
also works with sets:
nums = {3, 4, 5}
for index, value in enumerate(nums):
print(index, value)
'''
Output
0 3
1 4
2 5
'''
tuples:
nums = (3, 4, 5)
for index, value in enumerate(nums):
print(index, value)
'''
Output
0 3
1 4
2 5
'''
and dictionaries:
fruit = {"apples": 3, "oranges": 4, "mangoes": 5}
for index, value in enumerate(fruit):
print(index, value)
'''
Output
0 apples
1 oranges
2 mangoes
'''
It doesn't look useful on dictionaries.
Use cases
enumerate
can help you if you find yourself in a situation which requires both indexes and items. It has the same time complexity as list lookup: O(n), so you have nothing to worry.
Thanks for reading. Adios βπΎπ§‘.
Β