1languages = ['Python', 'C', 'C++', 'C#', 'Java']
2
3#Bad way
4i = 0 #counter variable
5for language in languages:
6 print(i, language)
7 i+=1
8
9#Good Way
10for i, language in enumerate(languages):
11 print(i, language)
12
1>>> for count, value in enumerate(values):
2... print(count, value)
3...
40 a
51 b
62 c
7
1list1 = ['1', '2', '3', '4']
2
3for index, listElement in enumerate(list1):
4 #What enumerate does is, it gives you the index as well as the element in an iterable
5 print(f'{listElement} is at index {index}') # This print statement is just for example output
6
7# This code will give output :
8"""
91 is at index 0
102 is at index 1
113 is at index 2
124 is at index 3
13"""
1>>> def my_enumerate(sequence, start=0):
2... n = start
3... for elem in sequence:
4... yield n, elem
5... n += 1
6...
7
1grocery = ['bread', 'milk', 'butter']
2
3for item in enumerate(grocery):
4 print(item)
5
6print('\n')
7for count, item in enumerate(grocery):
8 print(count, item)
9
10print('\n')
11# changing default start value
12for count, item in enumerate(grocery, 100):
13 print(count, item)
1enumerate(iterable, start=0)
2
3Parameters:
4Iterable: any object that supports iteration
5Start: the index value from which the counter is
6 to be started, by default it is 0
1Return type: < type 'enumerate' >
2[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
3[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]