Rotate a Python list
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
from collections import deque if __name__ == '__main__': nums = list(range(5)) k = 2 x = deque(nums) x.rotate(k) print(x) # [3, 4, 0, 1, 2] |
To rotate k steps to the left, pass the negative value of k, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
from collections import deque if __name__ == '__main__': nums = list(range(5)) k = 2 x = deque(nums) x.rotate(-k) print(x) # [2, 3, 4, 0, 1] |
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:
|
1 2 3 4 5 6 7 8 9 10 |
import numpy as np if __name__ == '__main__': nums = list(range(5)) k = 2 x = np.roll(nums, k) print(x) # [3, 4, 0, 1, 2] |
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:
|
1 2 3 4 5 6 7 8 9 10 |
import numpy as np if __name__ == '__main__': nums = list(range(5)) k = 2 x = np.roll(nums, -k) print(x) # [2, 3, 4, 0, 1] |
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
def rotate(seq, k): return seq[k:] + seq[:k] if __name__ == '__main__': nums = list(range(5)) k = 2 x = rotate(nums, k) print(x) # [2, 3, 4, 0, 1] |
To left-rotate, pass the negative value of k as before:
|
1 2 3 4 5 6 7 8 9 10 11 |
def rotate(seq, k): return seq[k:] + seq[:k] if __name__ == '__main__': nums = list(range(5)) k = 2 x = rotate(nums, -k) print(x) # [3, 4, 0, 1, 2] |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)