+2 votes
in Programming Languages by (11.5k 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

0 votes
by (20k points)

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]

...