The enumerate() function is a powerful tool that takes an iterable (list, tuple, string, etc.) and returns an enumerate object that produces tuples of (index, element). It’s the Pythonic way to access both the position and value while iterating.
enumerate() eliminates the need for manual index tracking, making your code cleaner and less error-prone.
By default, enumerate starts at 0, but you can change this:
frutas = ["manzana", "banana", "naranja", "uva"]print("Enumerate comenzando en 1:")for numero, fruta in enumerate(frutas, start=1): # Now indices go from 1 to 4 instead of 0 to 3 print(f"{numero}. {fruta}")# Output:# 1. manzana# 2. banana# 3. naranja# 4. uva
Why Use start=1?
Starting at 1 is perfect for:
Creating numbered menus
Displaying ranked lists
Showing human-friendly positions (people count from 1, not 0)
palabra = "Python"print("Enumerate con strings:")for posicion, letra in enumerate(palabra): # Each character of the string is treated as an element print(f"Posición {posicion}: '{letra}'")# Output:# Posición 0: 'P'# Posición 1: 'y'# Posición 2: 't'# Posición 3: 'h'# Posición 4: 'o'# Posición 5: 'n'
Combine enumerate with if statements for powerful filtering:
numeros = [10, 25, 30, 45, 50, 15, 60]print("Encontrar índices de números mayores a 30:")for idx, num in enumerate(numeros): if num > 30: print(f"El número {num} está en el índice {idx}")# Output:# El número 45 está en el índice 3# El número 50 está en el índice 4# El número 60 está en el índice 6
# Create a list of tuples (index, value squared)cuadrados = [(i, x**2) for i, x in enumerate([1, 2, 3, 4, 5])]print("Lista de comprensión con enumerate:")print(cuadrados)# Result: [(0, 1), (1, 4), (2, 9), (3, 16), (4, 25)]
Combine enumerate with zip for parallel iteration:
nombres = ["Ana", "Luis", "María"]edades = [25, 30, 28]print("Combine enumerate con zip:")for idx, (nombre, edad) in enumerate(zip(nombres, edades)): # zip combines both lists, enumerate adds the index print(f"{idx + 1}. {nombre} tiene {edad} años")# Output:# 1. Ana tiene 25 años# 2. Luis tiene 30 años# 3. María tiene 28 años
Combining enumerate() with zip() is powerful for processing multiple related lists simultaneously.
numeros = [1, 3, 5, 3, 7, 3, 9]target = 3posiciones = [idx for idx, num in enumerate(numeros) if num == target]print(f"Positions of {target}: {posiciones}")# Output: Positions of 3: [1, 3, 5]
Pattern: Process Every Nth Element
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']# Process every 3rd elementfor idx, item in enumerate(items): if idx % 3 == 0: print(f"Processing {item} at index {idx}")
Pattern: Create Numbered Labels
tareas = ["Lavar platos", "Hacer tarea", "Llamar a mamá"]labeled = [f"{i+1}. {tarea}" for i, tarea in enumerate(tareas)]print(labeled)# ['1. Lavar platos', '2. Hacer tarea', '3. Llamar a mamá']
# enumerate() is efficient - it's an iterator, not creating a full listfor idx, item in enumerate(huge_list): # Memory efficient, even with millions of items process(idx, item)
enumerate() returns an iterator, so it’s memory-efficient even with very large collections.