Jared
Jared

Reputation: 555

How do I move the last item in a list to the front in python?

I searched thoroughly but can't find anything relating to this exact specific. I have a list:

a = [two, three, one]

I want to move one to the front, so it becomes:

a = [one, two, three]

The thing is, it could be ANY amount of numbers in the list. Assume there is no way of knowing whether there will be 50 items or 3.

Upvotes: 26

Views: 31304

Answers (6)

PythonProgrammi
PythonProgrammi

Reputation: 23443

Fun

insert

The best way was just indicates as:

>>> a = ["two","three","one"]
>>> a.insert(0,a.pop())
>>> a
['one', 'two', 'three']

pop

But, if I should do something original, I will make this:

>>> a = ["two","three","one"]
>>> a = [a.pop()] + a
>>> a
['one', 'two', 'three']

slice

And, last exercize, this:

>>> a = ["two","three","one"]
>>> a = [a[-1]] + a[:-1]
>>> a
['one', 'two', 'three']

Upvotes: 4

hayes robin
hayes robin

Reputation: 73

If you want to move first item of a list to last , you can use this -

lst=['one','two','three']
lst.insert(len(lst),lst.pop(0)) # result ['two','three','one']

Upvotes: 3

Cat Plus Plus
Cat Plus Plus

Reputation: 129774

Basically:

a.insert(0, a.pop())

Consider using collections.deque if you're doing that often, though.

Upvotes: 37

eyquem
eyquem

Reputation: 27575

a = ['two', 'three', 'one']
a = a[-1:] + a[0:-1]
print a



a = ['two', 'three', 'one']

a[0:0] = a[-1:]
del a[-1]
print a

I prefer the second manner because the operations are in place, while in the first manner a new list is created

Upvotes: 2

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

You can use the following code:

a.insert(0, a.pop())

Upvotes: 7

Tugrul Ates
Tugrul Ates

Reputation: 9687

The -1 index relates to the last item.

a = a[-1:] + a[:-1]

This will work for any number of elements in list.

Upvotes: 17

Related Questions