Rotating a list means shifting its elements to the left or right by a certain number of positions. In this article, we will explore Various ways to rotate a list The simplest way to rotate a list is by using slicing. Slicing allows us to break the list into two parts and rearrange them.
a = [1, 2, 3, 4, 5]
# Number of positions to rotate
n = 2
# Rotate right by 2
rotated_list = a[-n:] + a[:-n]
print(rotated_list)
Output
[4, 5, 1, 2, 3]
Other methods by which we can rotate a list are:
Table of Content
Using deque.rotate()
Python's collections.deque is a double-ended queue that supports rotating the list efficiently. It has a built-in rotate() method which makes rotating the list easy and fast.
from collections import deque
a = [1, 2, 3, 4, 5]
d = deque(a)
# Rotate 2 positions to the right
d.rotate(2)
# Convert back to list if needed
rotated_list = list(d)
print(rotated_list)
Output
[4, 5, 1, 2, 3]
Using Loop and pop()
Another way to rotate a list is by using a loop with the pop() method. The pop() method removes and returns the last element, which can be added to the front of the list.
a = [1, 2, 3, 4, 5]
# Number of positions to rotate
n = 2
for _ in range(n):
# Rotate right by 2
a.insert(0, a.pop())
print(a)
Output
[4, 5, 1, 2, 3]
List Using numpy
When we are working with numerical data or with large data , the numpy library can help rotate lists easily. Here's how to do it with numpy.
import numpy as np
def rotate_list(a, n):
return np.concatenate((a[-n:], a[:-n]))
a = [1, 2, 3, 4, 5]
n = 2 # Rotate by 2 positions
rotated = rotate_list(a, n)
print(rotated)
Output
[4 5 1 2 3]