The enumerate()
function adds a counter to a sequence and returns a tuple containing the index number and the corresponding element in each iteration of the loop.
It is especially useful when we need to know both the index and the value of each element during iteration.
Syntax of enumerate()
The general syntax of enumerate()
is:
enumerate(sequence, start=0)
- sequence: The sequence to iterate over.
- start: The initial value of the counter. Default is 0.
enumerate()
is efficient and optimized to handle large volumes of data, as it does not create an additional list in memory but returns an iterator.
It is compatible with all types of iterables in Python, including lists, tuples, strings.
Basic Example
In this example, enumerate is used to loop through a list of names, printing the index and the name of each element.
names = ['Luis', 'María', 'Carlos', 'Ana']
for index, name in enumerate(names):
print(f"Index {index}: {name}")
# Output:
# Index 0: Luis
# Index 1: María
# Index 2: Carlos
# Index 3: Ana
Practical Examples
Specifying a Start for the Counter
This shows how to use enumerate by specifying a different starting value for the index counter. In this case, the count starts at 1 instead of 0.
names = ['Luis', 'María', 'Carlos', 'Ana']
for index, name in enumerate(names, start=1):
print(f"Student {index}: {name}")
# Output:
# Student 1: Luis
# Student 2: María
# Student 3: Carlos
# Student 4: Ana
Using enumerate() with Other Data Types
This example shows how enumerate can also be used with other types of sequences, such as strings, to get the index and the character in each iteration.
string = "Python"
for index, character in enumerate(string):
print(f"Index {index}: {character}")
# Output:
# Index 0: P
# Index 1: y
# Index 2: t
# Index 3: h
# Index 4: o
# Index 5: n
Creating a Dictionary from enumerate()
In this example, enumerate is used in a dictionary comprehension to create a dictionary that maps indices to values from a list of countries.
countries = ['España', 'Francia', 'Italia']
dictionary_countries = {index: country for index, country in enumerate(countries)}
print(dictionary_countries)
# Output: {0: 'España', 1: 'Francia', 2: 'Italia'}