Reputation: 555
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
Reputation: 23443
The best way was just indicates as:
>>> a = ["two","three","one"]
>>> a.insert(0,a.pop())
>>> a
['one', 'two', 'three']
But, if I should do something original, I will make this:
>>> a = ["two","three","one"]
>>> a = [a.pop()] + a
>>> a
['one', 'two', 'three']
And, last exercize, this:
>>> a = ["two","three","one"]
>>> a = [a[-1]] + a[:-1]
>>> a
['one', 'two', 'three']
Upvotes: 4
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
Reputation: 129774
Basically:
a.insert(0, a.pop())
Consider using collections.deque
if you're doing that often, though.
Upvotes: 37
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
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