Search code examples
pythonpython-3.xlistindexingreverse

How to loop a list in reverse order and skip last element


I know I can have for i in x[::-1]: to loop through a list in reverse order. But what if I want to skip the last element then traverse from high to low? for i in x[-1:0:-1] does not work

x = [1,2,3,4,5]
=> 4,3,2,1         #  desired

for i in x[-1:-1]:
    print(i)

# it does not work

Solution

  • You need to begin from -2 as -1 starts from the last element:

    for i in x[-2::-1]:
        print(i)
    

    Alternatively, you can use reversed with list slicing:

    for i in reversed(x[:-1]):
        print(i)