3

I have a list:

a = [1, 2, 3, 4, 5, 6, 7]

I want last element to come in first place and rest all elements to shift to next place.My expected result is:

a = [7, 1, 2, 3, 4, 5, 6]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Shubham Sharda
  • 653
  • 1
  • 6
  • 5

2 Answers2

12

To alter the list in-place, simply pop it off and insert it at the front:

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

Demo:

>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> a.insert(0, a.pop())
>>> a
[7, 1, 2, 3, 4, 5, 6]

However, note that all other elements have to be shifted up a place for this, so internally O(N) steps are taken (for N elements in the list).

You could also create a new list object by using slicing and concatenation:

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

but this is more inefficient still as now you have to create 3 new list objects, doubling the number of steps taken.

If you need to rotate the list regularly, you may want to use a collections.deque() object instead:

from collections import deque

a = deque([1, 2, 3, 4, 5, 6, 7])
a.rotate(1)

deque rotation is a O(K) process, where K is the number of steps rotated.

The disavantage of a deque is that arbitrary indexing can cost you up to O(N) steps to get to element N in the list, whereas indexing to any element in a regular list is O(1) constant time.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

Pop it and then insert it.

>>> a = [1,2,3,4,5,6,7]
>>> a.insert(0, a.pop())
>>> a
[7, 1, 2, 3, 4, 5, 6]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97