DEV Community

loading...

Looping over a collection

Zeeshan Asgar
Software Engineer | Full Stack Developer | Microservices Enthusiast
・1 min read

Consider the following collection(list):

fruits = ['apple', 'grapes', 'mango', 'banana', 'orange']
Enter fullscreen mode Exit fullscreen mode

To loop over the list fruits

for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

To loop in reverse over the list fruits

for fruit in reversed(fruits):
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

To get the indices of the list fruits

for i, fruit in enumerate(fruits):
    print(f'{i} - {fruit}')
Enter fullscreen mode Exit fullscreen mode

Output of enumerate()

0 - apple
1 - grapes
2 - mango
3 - banana
4 - orange
Enter fullscreen mode Exit fullscreen mode

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:

  1. iterable - an object that supports iteration like list, tuple etc.
  2. 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}')
Enter fullscreen mode Exit fullscreen mode

Output

1 - apple
2 - grapes
3 - mango
4 - banana
5 - orange
-----------
100 - apple
101 - grapes
102 - mango
103 - banana
104 - orange
Enter fullscreen mode Exit fullscreen mode

Discussion (0)