In Python, the enumerate() function is a built-in function that allows you to iterate over a sequence (like a list, tuple, or string) and access both the elements and their indexes.
Here's an example of using enumerate() to iterate over a list:
fruits = ["apple", "banana", "cherry"]for i, fruit in enumerate(fruits): print(i, fruit) |
In this example, we define a list called fruits containing three fruits. We then use the enumerate() function to iterate over the elements of the list and access their indexes. Inside the loop, the variable i takes on the index of each element, and the variable fruit takes on the value of each element.
You can also specify the starting index of the enumeration using the start argument. For example:
fruits = ["apple", "banana", "cherry"]for i, fruit in enumerate(fruits, start=1): print(i, fruit) |
In this example, we use the start argument to specify that the enumeration should start at 1 instead of the default value of 0.
I hope this helps! Let me know if you have any other questions.