Python enumerate() Function

In Python, the enumerate() function is a built-in function that allows you to iterate over a sequence (such as a list, tuple, or string) while keeping track of the index or position of each element. The enumerate() function returns an iterable object that produces tuples containing both the index and the corresponding element in the sequence.

Enumerate a List

fruits = ['apple', 'banana', 'orange', 'grape'] for index, fruit in enumerate(fruits): print(f"Index {index}: {fruit}")
Output: Index 0: apple Index 1: banana Index 2: orange Index 3: grape

In this example, the enumerate() function is used to loop through the fruits list. It assigns the index of each element to the variable index, and the element itself to the variable fruit. The loop then prints both the index and the corresponding fruit.

Enumerate with a Custom Start Index

colors = ['red', 'green', 'blue'] for index, color in enumerate(colors, start=1): print(f"Color {index}: {color}")
Output: Color 1: red Color 2: green Color 3: blue

In this example, the enumerate() function starts the index from 1 instead of the default 0. This is achieved by passing the start=1 argument to the function.

Enumerate a String

message = "Hello, World!" for index, char in enumerate(message): print(f"Character {index}: {char}")
Output: Character 0: H Character 1: e Character 2: l Character 3: l Character 4: o Character 5: , Character 6: Character 7: W Character 8: o Character 9: r Character 10: l Character 11: d Character 12: !

In this example, the enumerate() function is used to iterate through each character in the message string. It assigns the index of each character to the variable index, and the character itself to the variable char.


Python Enumerate

Python Enumerate Vs Python For Loops

The enumerate() function in Python provides the index of the current element along with its corresponding value. In contrast, a for loop enables sequential iteration over the elements in a sequence, allowing you to perform a specific action for each element. While both approaches facilitate iteration over a sequence, the enumerate() function grants access to the index of the current element, which can be particularly useful in certain situations, providing valuable positional information during the iteration process.

Conclusion

The enumerate() function is a handy tool whenever you need to access both the index and the value of elements while iterating through a sequence. It simplifies code and makes it more readable, especially in scenarios where you require the position information along with the element.