how to iterate through a list from last position to first# in python

You can use a negative step in a slice to iterate backward through a list.

Example code:

main.py
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)-1, -1, -1):
    print(my_list[i])
88 chars
4 lines

This code will print each element in the list my_list starting from the last position to the first.

Alternatively, you can also use the reversed() function to iterate backwards through the list.

Example code:

main.py
my_list = [1, 2, 3, 4, 5]
for i in reversed(my_list):
    print(i)
67 chars
4 lines

This will also print out the elements from last position to first.

related categories

gistlibby LogSnag