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 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