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

The enumerate() function is used to iterate through the sequence and retrieve the index position and its corresponding value at the same time.

For i,v in enumerate([‘Python’,’Java’,’C++’]):
print(i,v)
0 Python
1 Java
2 C++
# enumerate using an index sequence
for count, item in enumerate([‘Python’,’Java’,’C++’], 10):

The enumerate() function in Python is used to iterate over a sequence (such as a list, tuple, or string) along with an index counter. It returns a tuple containing the index and the corresponding item in the sequence for each iteration. This is particularly useful when you need to keep track of the index while iterating over elements of a sequence.

Here’s a simple example:

python
my_list = ['apple', 'banana', 'orange']

for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")

This will output:

yaml
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange

As you can see, enumerate() provides a convenient way to iterate over both the index and the value of elements in a sequence simultaneously.