Language: EN

uso-de-enumerate-en-python

Use of enumerate() in Python

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 particularly 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. By default, it 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 kinds of iterables in Python, including lists, tuples, and strings.

Basic Example

In this example, enumerate is used to iterate over 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

Usage Examples

Specifying a Start for the Counter

Here is how to use enumerate by specifying a different starting value for the index counter. In this case, the counting 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, char in enumerate(string):
    print(f"Index {index}: {char}")

# 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']

countries_dict = {index: country for index, country in enumerate(countries)}
print(countries_dict)

# Output: {0: 'España', 1: 'Francia', 2: 'Italia'}