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:

  1. Create a new empty list.
  2. 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.
  3.  Now add the remaining elements in the array to the list using the extend() function.
  4. The array is rotated.

Pseudocode for the above steps:

rotLeft(array, num_of_elements):

b = []

start

                 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)
Output:
[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.

Note:

  1. There are various solutions for rotation of array problem in python.
  2. This is a short solution of O(n) time complexity.
  3. In this similar way, the right rotation can also be done.
  4. 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?

Leave a Reply

Your email address will not be published. Required fields are marked *