What is the purpose of the enumerate() function in Python?
Python > Python Function > Python Function
275
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.
This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.