Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Make last item of array become the first

Tags:

python

list

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.

like image 722
BorrajaX Avatar asked Oct 11 '12 17:10

BorrajaX


People also ask

How do you move the last element first in Python?

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.

How do you call the last element of an array in Python?

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.

How do you index the last item in a 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.


1 Answers

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
like image 179
Martijn Pieters Avatar answered Nov 03 '22 17:11

Martijn Pieters