enumerate a list in python

To enumerate a list in Python, we can use the built-in enumerate() function, which returns an iterator that yields pairs of elements and their index in the list. Here's an example:

main.py
my_list = ['apple', 'banana', 'orange']
for i, item in enumerate(my_list):
    print(i, item)
94 chars
4 lines

Output:

main.py
0 apple
1 banana
2 orange
26 chars
4 lines

In the above example, we first create a list my_list with three elements. We then use a for loop to iterate over the list using enumerate(my_list) as the iterable. In each iteration, we unpack the pair of the current index i and the current element item using i, item = .... Finally, we print both the index and the element on a separate line inside the loop body.

gistlibby LogSnag