uso-de-enumerate-en-python

Use of enumerate() in Python

  • 2 min

The enumerate() function adds a counter to a sequence and returns a tuple containing the index number and the corresponding element in each loop iteration.

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)
Copied!
  • sequence: The sequence to iterate over.
  • start: Initial value for the counter. By default, it is 0.

enumerate() is efficient and optimized for handling 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 iterate through a list of names, printing the index and 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
Copied!

Practical Examples