enumerate pyton code example

Example 1: enumerate in python

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)

Example 2: enumerate python

for index,char in enumerate("abcdef"):
  print("{}-->{}".format(index,char))
  
0-->a
1-->b
2-->c
3-->d
4-->e
5-->f

Example 3: enumerate python

#Enumerate in python
l1 = ['alu','noodles','vada-pav','bhindi']
for index, item in enumerate(l1):
    if index %2 == 0:
        print(f'jarvin get {item}')

Example 4: enumerate in python

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
"""

Example 5: enumerate in python

enumerate(iterable, start=0)

Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is 
              to be started, by default it is 0

Example 6: how to use enumerate in python

l1 = ["eat","sleep","repeat"] 
  
# printing the tuples in object directly 
for ele in enumerate(l1): 
    print ele 
print 
# changing index and printing separately 
for count,ele in enumerate(l1,100): 
    print count,ele