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)
for index,subj in enumerate(subjects):
print(index,subj) ## enumerate will fetch the index
0 Statistics
1 Artificial intelligence
2 Biology
3 Commerce
4 Science
5 Maths
rhymes=['check','make','rake']
for rhyme in enumerate(rhymes):
print(rhyme)
#prints out :
(0, 'check')
(1, 'make')
(2, 'rake')
#basically just prints out list elements with their index
# 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
languages = ["Python", "C", "C++", "C#", "Java"]
counter = 1
for item in languages:
print(counter, item)
counter += 1
for item in enumerate(languages):
print(item[0], item[1])
for num,lang in enumerate(languages):
print(num,lang)
[print(num,lang) for num,lang, in enumerate(languages)]
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
"""
# For loop where the index and value are needed for some operation
# Standard for loop to get index and value
values = ['a', 'b', 'c', 'd', 'e']
print('For loop using range(len())')
for i in range(len(values)):
print(i, values[i])
# For loop with enumerate
# Provides a cleaner syntax
print('
For loop using builtin enumerate():')
for i, value in enumerate(values):
print(i, value)
# Results previous for loops:
# 0, a
# 1, b
# 2, c
# 3, d
# 4, e
# For loop with enumerate returning index and value as a tuple
print('
Alternate method of using the for loop with builtin enumerate():')
for index_value in enumerate(values):
print(index_value)
# Results for index_value for loop:
# (0, 'a')
# (1, 'b')
# (2, 'c')
# (3, 'd')
# (4, 'e')