The enumerate() function adds a counter to an iterable and returns it as an enumerate object. This enumerate object can then be used directly in a for loop or converted into a list of tuples using the list() function. Each tuple contains a pair of an index (starting from zero by default) and the corresponding item from the iterable.

What Does Enumerate Do in Python

Basic Syntax

  • iterable: The sequence to be enumerated.
  • start: The starting index of the counter (default is 0).
enumerate(iterable, start=0)

Example

Here’s a simple example of how to use enumerate():

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:

0 apple
1 banana
2 cherry

Conclusion

The enumerate() function is a convenient and efficient way to access both the index and the value of items in a sequence during iteration. It eliminates the need for manually incrementing a counter variable, making your code cleaner and more readable. By using enumerate(), you can handle tasks that require indexing with greater ease, such as when you need to modify items at specific positions or when debugging.

Simon

102 Articles

I love talking about tech.