enumerate for loop python code example
Example 1: enumerate in python
languages = ['Python', 'C', 'C++', 'C#', 'Java']
i = 0
for language in languages:
print(i, language)
i+=1
for i, language in enumerate(languages):
print(i, language)
Example 2: for loop with enumerate python
presidents = ["Washington", "Adams", "Jefferson"]
for num, name in enumerate(presidents, start=0):
print("President {}: {}".format(num, name))
Example 3: for enumerate python
for key, value in enumerate(["p", "y", "t", "h", "o", "n"]):
print key, value
"""
0 p
1 y
2 t
3 h
4 o
5 n
"""
Example 4: enumerate in python
list1 = ['1', '2', '3', '4']
for index, listElement in enumerate(list1):
print(f'{listElement} is at index {index}')
"""
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