This is a very simple question, but I haven’t seem to be able to find a satisfactory answer for it.
What is the best way, in Python, make the last item of a list become the first one “pushing” the rest of the list.
Something that does:
>>> a=[1,2,3,4]
>>> a[?????]
[4, 1, 2, 3]
I know I can always play with len, list concatenation…
>>> a=[1,2,3,4]
>>> [a[len(a)-1]] + a[0:len(a)-1]
[4, 1, 2, 3]
But that doesn’t look right… “Pythonic“, if you may
Thank you in advance.
Slicing is a little smarter than that; you can use negative indices to count from the end:
Demo:
This works for an arbitrary number of elements to be moved to the front:
Using slicing like this is comparable in speed to using
.insert()+.pop()(on a short list):but wins hands down if you need to shift more than one element: