How to rotate an array in Python
In this tutorial, we will see how to rotate an array in Python by a given number of elements. Rotating an array is a process involving the shifting of the elements by n positions. This shifting of elements to the left is left rotation and shifting to the right is known as right rotation.
Steps for left rotation of array in Python:
- Create a new empty list.
- Append the array elements to the new list, leaving the elements that have to be rotated. For example, if the array has to be rotated by 2, leave behind the first two array elements.
- Now add the remaining elements in the array to the list using the extend() function.
- The array is rotated.
Pseudocode for the above steps:
b = 
for i = num_of_elements to i = len(arr):
add elements to b
add elements left in arr to b
def rotLeft(a, d): b =  for i in range(-d,len(a)): b.append(a[i]) b.extend(a[0:d]) return b rotLeft([1,2,3,4,5,6,7],2) rotLeft([12,45,20,11,10,56],1)
[3, 4, 5, 6, 7, 1, 2]
[45, 20, 11, 10, 56, 12]
Here, the first n elements of the array have moved to the end in both the cases.
- There are various solutions for rotation of array problem in python.
- This is a short solution of O(n) time complexity.
- In this similar way, the right rotation can also be done.
- The only change in right rotation is that elements from last are shifted to the front.
Also read: How to Implement Segment Tree in Python?