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 = []


                 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)):
    return b

[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.


  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?

3 responses to “How to rotate an array in Python”

  1. chris says:

    the above code is incorrect, as the size of the return array is always >= to the original array.

    A simpler solution is:

    def rotLeft(a, b):
    return a[b: len(a)] + a[0: b]

  2. Jean says:

    Hi, could you please explain this answer? Im trying to grasp it.

  3. Sumeet Upendra Singh says:

    def rotLeft(a, b):
    return a[b: len(a)] + a[0: b]

Leave a Reply

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