Curriculum
In Python, enumeration is a built-in function that allows you to iterate over a sequence and keep track of the index of the current item. Enumeration is useful when you need to access both the value and index of each item in a sequence.
Here is an example of how to use the enumerate function in Python:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
In this example, we create a list of fruits and use the enumerate function to iterate over the list. The enumerate function returns a tuple containing the index and value of each item in the list. We use tuple unpacking to assign the index and value to the variables index and fruit, respectively. We then print the index and value of each item in the list.
The output of this code will be:
0 apple 1 banana 2 cherry
As you can see, the enumerate function allows us to access the index and value of each item in the list, making it easier to work with the items in the list.
You can also specify a starting value for the index by passing a second argument to the enumerate function. For example:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
In this example, we use the enumerate function with a starting value of 1. The output of this code will be:
1 apple 2 banana 3 cherry
As you can see, the enumerate function allows us to access the index and value of each item in the list, starting with the value 1 instead of the default value 0.