jacobcan118
jacobcan118

Reputation: 9037

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

Upvotes: 5

Views: 5554

Answers (4)

Hildy
Hildy

Reputation: 510

The answers that involve list slicing are probably best, but it could also be done with enumerate.

x = [1, 2, 3, 4, 5]
for index, value in enumerate(reversed(x)):
    val = value-1
    if val:
        print(val)

Again, the slicing answers are better in a "Big O" sense, but it doesn't hurt to see a few ways to do a thing.

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71570

can reverse after removing for the loop:

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

Upvotes: 0

user10030086
user10030086

Reputation:

You can use double slicing like this

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

Upvotes: 2

jpp
jpp

Reputation: 164623

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)

Upvotes: 7

Related Questions