+2 votes
in Programming Languages by (77.2k points)
How can I move the last 3 elements of a list to the first 3 positions and shift the remaining elements to the right?

e.g.

[11, 12, 13, 14, 15, 16, 17]
to
[15, 16, 17, 11, 12, 13, 14]

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

If you want to move the last N elements to the front of the list, you can use the following code:

a[-N:]+a[:-N]

E.g.- To move 3 elements, I used a[-3:]+a[:-3].

>>> a=[11,12,13,14,15,16,17]
>>> a
[11, 12, 13, 14, 15, 16, 17]
>>> a[-3:]+a[:-3]
[15, 16, 17, 11, 12, 13, 14]


...