Consider the following collection(list):
fruits = ['apple', 'grapes', 'mango', 'banana', 'orange']
To loop over the list fruits
for fruit in fruits:
print(fruit)
To loop in reverse over the list fruits
for fruit in reversed(fruits):
print(fruit)
To get the indices of the list fruits
for i, fruit in enumerate(fruits):
print(f'{i} - {fruit}')
Output of enumerate()
0 - apple
1 - grapes
2 - mango
3 - banana
4 - orange
In the previous code snippet, we have used enumerate
to loop over the list.
enumerate(iterable, start=0)
enumerate()
allows us to loop over an iterable and provides an automatic counter. It takes two parameters:
-
iterable
- an object that supports iteration like list, tuple etc. -
start
- specifies the starting index of the counter. It is optional and defaults to 0.
Example
for i, fruit in enumerate(fruits, start=1):
print(f'{i} - {fruit}')
print("-----------")
for i, fruit in enumerate(fruits, start=100):
print(f'{i} - {fruit}')
Output
1 - apple
2 - grapes
3 - mango
4 - banana
5 - orange
-----------
100 - apple
101 - grapes
102 - mango
103 - banana
104 - orange
Top comments (0)