Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
  Signup/Sign In

What are the Efficient ways to rotate a List in Python?

In this article, we will learn to rotate a list in Python. We will use some built-in functions, simple approaches, and some custom codes as well. Let's first have a quick look over what is a list in Python.

Python List

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values.

list1 = ["Ram", "Arun", "Kiran"]
list2 = [16, 78, 32, 67]
list3 = ["apple", "mango", 16, "cherry", 3.4]

Rotation of a list means pushing and pulling elements from both ends of the list. In the left rotation, each element of the list is shifted to its left side by one position and the first element is added to the end of the list. Similarly, in the right rotation, each element of the list is shifted to its right side by one position and the last element is added to the start of the list. This process is followed a specified number of times. Now, we will discuss various methods to rotate a list. These methods can perform both Left Rotations as well as Right Rotation by taking the number of rotations as input.

Example: Rotate a List by using the Slicing Technique

This method simply rotates a list in a one-liner code. This is the most generic and efficient method to achieve rotation of a list. It performs a slicing operation by taking the number of rotations. In this case, it rotates the list l1, 3 spaces to the right and left side. It joins the latter sliced part of the list with the initial sliced part of the list. You can provide any number of rotations according to the need.

#input list
l1 = [1, 4, 6, 7, 2] 
print("Original List : " + str(l1)) 

#left rotate by 3 
l1 = l1[3:] + l1[:3] 
print("Left rotation of List by 3 : " + str(l1)) 

#right rotate by 3
l1 = l1[-3:] + l1[:-3] 
print("Right rotation of List by 3 : " + str(l1)) 


Original List : [1, 4, 6, 7, 2]
Left rotation of List by 3 : [7, 2, 1, 4, 6]
Right rotation of List by 3 : [1, 4, 6, 7, 2]

Example: Rotate a List using List Comprehension

This method is performed in one line using List Comprehension. In this method, we just reassign the index to each value to a specific position after rotation. Just replace 3 with any number of rotation you want.

#input list
l1 = [1, 4, 6, 7, 2] 
print("Original List : " + str(l1)) 

#left rotate by 3 
l1 = [l1[(i + 3) % len(l1)] for i, x in enumerate(l1)] 
print ("Left rotation of List by 3 : " + str(l1)) 

#right rotate by 3 
l1 = [l1[(i - 3) % len(l1)] for i, x in enumerate(l1)] 
print ("Right rotation of List by 3 : " + str(l1)) 


Original List : [1, 4, 6, 7, 2]
Left rotation of List by 3 : [7, 2, 1, 4, 6]
Right rotation of List by 3 : [1, 4, 6, 7, 2]

Example: Rotate a List using Collections Module

This method imports deque from the collections module of Python. deque() class provides rotate() function to perform List Rotation. This is also an efficient way to rotate a list as it is faster than the slicing technique. It is optimized for pulling and pushing on both ends.

deque() - It takes a list as an argument and converts it to a deque object.

rotate() - It is applied to the deque object and takes the number of rotations as an argument. It simply rotates the list.

Negative indexes are given to perform left rotation while positive indexes are given to perform right rotation.

from collections import deque 

#input list
l1 = [1, 4, 6, 7, 2] 
print ("Original List : " + str(l1)) 

#left rotate by 3 
l1 = deque(l1) 
l1.rotate(-3) 
l1 = list(l1) 
print ("Left rotation of List by 3 : " + str(l1)) 

#right rotate by 3
l1 = deque(l1) 
l1.rotate(3) 
l1 = list(l1) 
print ("Right rotation of List by 3 : " + str(l1)) 


Original List : [1, 4, 6, 7, 2]
Left rotation of List by 3 : [7, 2, 1, 4, 6]
Right rotation of List by 3 : [1, 4, 6, 7, 2]

Example: Right Rotation of a List by Appending Elements to a New List

This method increases the Space Complexity of the program. This method creates an empty list and stores the modified list into a new list. It works similar to list comprehension. It iterates the first list one by one and then places the elements at suitable positions in a second list using the append() function.

#number of rotations
num = 3
l1 = [1, 2, 3, 4, 5, 6] 
l2 = [] 

# Will add values from n to the new list 
for ele in range(len(l1) - num, len(l1)):
    l2.append(l1[ele])
# Will add the values before n to the end of new list
for ele in range(0, len(l1) - num):
    l2.append(l1[ele]) 

print("Right rotation of List by 3 : " + str(l2)) 


Right rotation of List by 3 : [4, 5, 6, 1, 2, 3]

Example: Right Rotation of a List using len() and Slicing Technique

This method also involves the Slicing technique but along with len() function.

#number of rotations
num = 3

#input list
l1 = [1, 2, 3, 4, 5, 6] 

l1 = (l1[len(l1) - num:len(l1)] + l1[0:len(l1) - num]) 

print("Right rotation of List by 3 : " + str(l1)) 


Right rotation of List by 3 : [4, 5, 6, 1, 2, 3]

Example: Rotation of a List using NumPy Module

Python's Numpy module provides a built-in roll() function to carry out the rotation on an array. Firstly, it creates an array by passing a range (starting value, last value(excluded)) using numpy.arange() function. Then, the array and the number of rotations are passed as arguments to numpy.roll() function.

import numpy

arr = numpy.arange(1,10) 
print("Orignial array : ", arr)

#right rotate by 3
print("Right rotation by 3 : ", numpy.roll(arr,3))

#left rotate by 3
print("Left rotation by 3 : ", numpy.roll(arr,-3))


Orignial array : [1 2 3 4 5 6 7 8 9]
Right rotation by 3 : [7 8 9 1 2 3 4 5 6]
Left rotation by 3 : [4 5 6 7 8 9 1 2 3]

Conclusion

In this article, we learned to rotate a list by using several built-in functions such as deque(), len(), append(), rotate(), numpy.roll() and also used list comprehension and slicing technique. We used some custom code as well. We discussed that out of all the methods the collections.deque is the most efficient method to carry out the list rotation operation. All these methods has Time Complexity equal to 0(n) due to one single iteration over the elements of the list.