Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to rotate a list in python

Tags:

python

list

What is the most efficient way to rotate a list in python? Right now I have something like this:

>>> def rotate(l, n): ...     return l[n:] + l[:n] ...  >>> l = [1,2,3,4] >>> rotate(l,1) [2, 3, 4, 1] >>> rotate(l,2) [3, 4, 1, 2] >>> rotate(l,0) [1, 2, 3, 4] >>> rotate(l,-1) [4, 1, 2, 3] 

Is there a better way?

like image 888
D R Avatar asked Jan 27 '10 20:01

D R


People also ask

How do I rotate a list in Python?

In Python, the easiest way to rotate items in a list is with the Python list pop(), insert(), and append() functions. You can also use the deque() data structure from the Python collections module to rotate a list. You can also use list slicing to rotate a list forward or backwards in Python.

How do you shift a list to the right in Python?

With Python, we can easily shift the items in a list both to the right or the left. To shift items to the left, we can remove the first element from the list with pop(), and then append it to the end of the list with the append() function. To shift items to the right, we can do the opposite.

How do you predefine a list in Python?

To initialize a list in Python assign one with square brackets, initialize with the list() function, create an empty list with multiplication, or use a list comprehension. The most common way to declare a list in Python is to use square brackets.


2 Answers

A collections.deque is optimized for pulling and pushing on both ends. They even have a dedicated rotate() method.

from collections import deque items = deque([1, 2]) items.append(3)        # deque == [1, 2, 3] items.rotate(1)        # The deque is now: [3, 1, 2] items.rotate(-1)       # Returns deque to original state: [1, 2, 3] item = items.popleft() # deque == [2, 3] 
like image 176
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 18:09

Ignacio Vazquez-Abrams


What about just using pop(0)?

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

like image 22
Jamgold Avatar answered Sep 21 '22 18:09

Jamgold