Jacek
Jacek

Reputation: 73

Iterate a list from second to last and then first element

I need to create for loop which iterate list from second element to the last and then it take first elements. Something like this:

x = [2, 133, 24]

for i in (x[1:] + x[0]):
     print(i)

result should be: 133, 24, 2

list cannot be changed and should be usable on lists with 2-10 elements Thanks for Your help

Upvotes: 0

Views: 1143

Answers (2)

Pacifa
Pacifa

Reputation: 23

You can use a modulo

x = [2, 133, 24]

start = 1
end = 3
for i in range(start,end+start):
    index = i % end
    print(x[index])

Upvotes: 0

SuperStew
SuperStew

Reputation: 3054

Just a small adjustment

for i in (x[1:] + [x[0]]):
     print(i)

Upvotes: 1

Related Questions