for loop in range of length list in python

You can iterate over a list using a for loop in Python. The easiest way to do it is to use the range function and the length of the list.

Here's an example:

main.py
my_list = [1, 2, 3, 4, 5]

for i in range(len(my_list)):
    print(my_list[i])
79 chars
5 lines

Output:

main.py
1
2
3
4
5
10 chars
6 lines

In the above code, range(len(my_list)) creates a range object that will generate the values 0, 1, 2, 3, 4. These values correspond to the indices of the list. The loop then goes through each index and prints the value stored at that index in the list.

related categories

gistlibby LogSnag