Python built-in Method - enumerate()

www.ig‮i‬ftidea.com

The enumerate() method is a built-in function in Python that allows you to iterate over a sequence while keeping track of the index of the current item. The method returns an iterator of tuples where the first element of each tuple is the index of the corresponding item, and the second element is the item itself.

Here is the syntax for enumerate() method:

enumerate(iterable, start=0)

where iterable is the sequence or collection that you want to iterate over, and start is the index that you want to start counting from (by default, start is 0).

Here's an example of how to use enumerate():

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

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

In this example, we use enumerate() to iterate over a list of fruits. The for loop assigns the index of each fruit to the index variable, and the fruit itself to the fruit variable. The output of the loop is:

0 apple
1 banana
2 cherry

You can also specify a value for the start parameter to change the starting index. Here's an example:

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

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

In this example, we use enumerate() with a start value of 1, so the first index is 1 instead of 0. The output of the loop is:

1 apple
2 banana
3 cherry

enumerate() can be useful when you need to iterate over a sequence and also need to keep track of the index of the current item. It can be used with any iterable object, including lists, tuples, strings, and dictionaries.