This post will discuss how to rotate a list in Python.

1. Using deque rotate() function

The collections.deque is a generalization of stacks and queues and support the rotate() function, which rotates the deque k steps to the right.

Download  Run Code

 
To rotate k steps to the left, pass the negative value of k, as shown below:

Download  Run Code

 
Note that the rotate() takes O(k) time in both the average and amortized worst cases.

2. Using numpy.roll() function

If you happen to be using NumPy already, you can use the roll() function that rotates the array elements along a given axis. To right-rotate the sequence by k positions, you can pass the list and an integer denoting the shift to the roll() function, as shown below:

 
The second argument to the roll() function denotes the total number of places by which elements are shifted. To rotate left, pass the negative value of k:

3. Using Slicing

You can also use slicing to create two new lists and return the concatenation of both lists. The following example shows how to rotate the list k positions to the right using slicing:

Download  Run Code

 
To left-rotate, pass the negative value of k as before:

Download  Run Code

 
Note that all the above solutions create a new list and does not in-place modify the original list.

That’s all about rotating a list in Python.