languages = ['Python', 'C', 'C++', 'C#', 'Java']
#Bad way
i = 0 #counter variable
for language in languages:
print(i, language)
i+=1
#Good Way
for i, language in enumerate(languages):
print(i, language)
# Python program to illustrate
# enumerate function in loops
l1 = ["eat", "sleep", "repeat"]
# printing the tuples in object directly
for ele in enumerate(l1):
print (ele)
>>>(0, 'eat')
>>>(1, 'sleep')
>>>(2, 'repeat')
# changing index and printing separately
for count, ele in enumerate(l1, 100):
print (count, ele)
>>>100 eat
>>>101 sleep
>>>102 repeat
# getting desired output from tuple
for count, ele in enumerate(l1):
print(count)
print(ele)
>>>0
>>>eat
>>>1
>>>sleep
>>>2
>>>repeat
list1 = ['1', '2', '3', '4']
for index, listElement in enumerate(list1):
#What enumerate does is, it gives you the index as well as the element in an iterable
print(f'{listElement} is at index {index}') # This print statement is just for example output
# This code will give output :
"""
1 is at index 0
2 is at index 1
3 is at index 2
4 is at index 3
"""
mydict = {1: 'a', 2: 'b'}
for i, (k, v) in enumerate(mydict.items()):
print("index: {}, key: {}, value: {}".format(i, k, v))
# which will print:
# -----------------
# index: 0, key: 1, value: a
# index: 1, key: 2, value: b
mydict = {1: 'a', 2: 'b'}
for i, (k, v) in enumerate(mydict.items()):
print(i,k,v)
#will print
# 0 1 a
# 1 2 b