enumerate() Function in Python

Python enumerate() Function

The enumerate() function in Python is a built-in function that allows you to iterate over a sequence (such as a list, tuple, or string) and retrieve both the index and the corresponding element at each iteration. It returns an iterator object that generates pairs of index-value tuples.

The syntax for using the enumerate() function is as follows:

enumerate(iterable, start=0)

The iterable parameter represents the sequence that you want to iterate over, and the optional start parameter specifies the starting index for enumeration. By default, the start parameter is set to 0.

Here's an example that demonstrates how to use the enumerate() function:

fruits = ['apple', 'banana', 'orange']

for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:

0 apple
1 banana
2 orange

In the example, enumerate(fruits) returns an iterator that produces tuples containing the index and corresponding fruit. The for loop iterates over each tuple, unpacking it into the index and fruit variables, and then prints them.

The enumerate() function is particularly useful when you want to iterate over a sequence and also need access to the index of each element.