search

What is the use of the "enumerate" function in Python?

The **enumerate** function in Python is used to iterate over a list (or other iterable object) and keep track of the index of each item in the list. The **enumerate** function takes in an iterable as an argument and returns an object that can be used in a for loop. In each iteration of the loop, the function returns a tuple that contains the index and the corresponding item.

For example, consider the following list:

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

If you want to loop over this list and print both the index and the item, you can use the ****enumerate**** function:

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

This will output:

0 apple
1 banana
2 cherry

The **enumerate** function is useful when you need to keep track of the index of an item in a list while looping over the list. It can also be used with other iterable objects such as tuples, strings, and sets.

For example, consider the following two lists:

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

You can use the **zip** function to combine these two lists into a single iterable object:

combined = zip(names, ages)

The resulting **combined** object can be used in a for loop, for example:

for name, age in combined:
    print(name, age)

This will output:

Alice 25
Bob 30
Charlie 35

Note that the **zip** function stops when the shortest input iterable is exhausted. In other words, the resulting object will only contain as many elements as the length of the shortest input iterable.

The **zip** function is useful when you want to combine two or more iterables into a single object for processing or for printing, for example.

Related Questions You Might Be Interested