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.
Method #2 : Using insert() + pop() This functionality can also be achieved using the inbuilt functions of python viz. insert() and pop() . The pop function returns the last element and that is inserted at front using the insert function.
To get the last element of the list using list. pop(), the list. pop() method is used to access the last element of the list.
Get the last element of the list using the “length of list - 1” as an index and print the resultant last element of the list. Get the last element of the list using − 1(negative indexing) as the index and print the resultant last element of the list.
Slicing is a little smarter than that; you can use negative indices to count from the end:
a[-1:] + a[:-1]
Demo:
>>> a=[1,2,3,4]
>>> a[-1:] + a[:-1]
[4, 1, 2, 3]
This works for an arbitrary number of elements to be moved to the front:
>>> a[-2:] + a[:-2]
[3, 4, 1, 2]
Using slicing like this is comparable in speed to using .insert()
+ .pop()
(on a short list):
>>> timeit.timeit('a[-1:] + a[:-1]', 'a=[1,2,3,4]')
0.59950494766235352
>>> timeit.timeit('a.insert(0,a.pop(-1))', 'a=[1,2,3,4]')
0.52790379524230957
but wins hands down if you need to shift more than one element:
>>> timeit.timeit('a[-2:] + a[:-2]', 'a=[1,2,3,4]')
0.58687901496887207
>>> timeit.timeit('a.insert(0,a.pop(-1));a.insert(0,a.pop(-1))', 'a=[1,2,3,4]')
1.0615170001983643
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With