Junior
What is the enumerate function in Python?
sobes.tech AI
Answer from AI
The enumerate() function adds a counter to an iterable and returns an iterator of pairs (counter, element). This is useful when you need to access both the elements of a collection and their indices simultaneously.
# Example of using enumerate() with a list
my_list = ['apple', 'banana', 'cherry']
for index, item in enumerate(my_list):
print(f"Index: {index}, Element: {item}")
# Output:
# Index: 0, Element: apple
# Index: 1, Element: banana
# Index: 2, Element: cherry
The default starting value of the counter is 0, but it can be set using the start argument.
# Example of using enumerate() with a specified start value
my_list = ['apple', 'banana', 'cherry']
for index, item in enumerate(my_list, start=1):
print(f"Identifier: {index}, Element: {item}")
# Output:
# Identifier: 1, Element: apple
# Identifier: 2, Element: banana
# Identifier: 3, Element: cherry
The enumerate() function returns an iterator, so to access the elements, you need to iterate over it or convert it to a list/tuple.
# Converting the result of enumerate() to a list of tuples
enumerated_list = list(enumerate(my_list))
print(enumerated_list)
# Output:
# [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
enumerate() is more "Pythonic" and readable than using range(len(...)) for iterating over indices.
Comparison of approaches:
enumerate() |
range(len(...)) |
|---|---|
| More readable | Less explicit |
| More efficient (does not require length retrieval) | Less efficient (requires length retrieval) |
| Direct access to element and index | Index access requires an additional operation |
# Using range(len()) - less preferred method
my_list = ['apple', 'banana', 'cherry']
for i in range(len(my_list)):
print(f"Index: {i}, Element: {my_list[i]}")