You can use ‘enumerate()‘ in Python to loop over an iterable (such as a list, tuple, or string) while also keeping track of the index of the current item.
1. Use ‘enumerate()‘ with a list:
my_list = ["apple", "grape", "mango", "peach", "lemon"]
for idx, item in enumerate(my_list):
print(idx, item)
The result:
0 apple
1 grape
2 mango
3 peach
4 lemon
To specify the start value for the index (for example, the start value of “1”):
my_list = ["apple", "grape", "mango", "peach", "lemon"]
for idx, item in enumerate(my_list, start=1):
print(idx, item)
The result:
1 apple
2 grape
3 mango
4 peach
5 lemon
2. Use ‘enumerate()‘ with a string:
my_string = "Universe"
for idx, letter in enumerate(my_string):
print(idx, letter)
The result:
0 U
1 n
2 i
3 v
4 e
5 r
6 s
7 e
3. Use ‘enumerate()‘ with a dictionary:
my_dict = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}
for idx, (key, value) in enumerate(my_dict.items()):
print(idx, key, value)
The result:
0 A 1
1 B 2
2 C 3
3 D 4
4 E 5