What is the purpose of the enumerate() function in Python?

Long Answer
Views 160

Answer:

The enumerate() function in Python is used to iterate over a sequence (such as a list, tuple, or string) and keep track of the index of the current item. It returns a sequence of tuples, each of which contains an index and the corresponding item from the original sequence.

Here's an example of using the enumerate() function to iterate over a list:


colors = ['red', 'green', 'blue']
for i, color in enumerate(colors):
    print(i, color)

# Output:
# 0 red
# 1 green
# 2 blue

In this example, the enumerate() function takes the list colors as an argument and returns a sequence of tuples, where each tuple contains an index and the corresponding color from the list. The for loop then iterates over the tuples, and the i and color variables are assigned the index and color, respectively, from each tuple.

The enumerate() function is useful when you need to iterate over a sequence and keep track of the index of each item, such as when processing a list or string, or when you need to retrieve the index of a specific item in a sequence.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Python, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.