Python Program for Array Rotation (original) (raw)

Last Updated : 13 Nov, 2025

Given an array of integers and a number d, the task is to rotate the array to the left by 'd' positions. In left rotation, each element moves one position to the left, and the first element moves to the end of the array.

**Example:

**Input: [1, 2, 3, 4, 5]
d=2

**Output: [3, 4, 5, 1, 2]

Using List Slicing

This method rotates an array by splitting it into two parts using slicing and then joining them in reverse order.

Python `

arr = [1, 2, 3, 4, 5, 6] d = 2 arr[:] = arr[d:] + arr[:d] print(arr)

`

**Explanation:

Using reverse() Method

This method rotates an array by reversing the entire array and then reversing its parts separately.

Python `

arr = [1, 2, 3, 4, 5, 6, 7, 8] d = 2 n = len(arr) arr.reverse()

arr[:n-d] = arr[:n-d][::-1] arr[n-d:] = arr[n-d:][::-1] print(arr)

`

Output

[3, 4, 5, 6, 7, 8, 1, 2]

**Explanation:

Using Temporary Array

This method rotates an array by storing the first 'd' elements in a temporary array, shifting the remaining elements left, and then appending the stored elements at the end.

Python `

arr = [1, 2, 3, 4, 5, 6, 7] d = 2 n = len(arr)

temp = arr[:d]
arr[:n-d] = arr[d:]
arr[n-d:] = temp

print(arr)

`

Output

[3, 4, 5, 6, 7, 1, 2]

**Explanation:

One by One Rotation

Python `

arr = [1, 2, 3, 4, 5, 6, 7] d = 2 n = len(arr)

for i in range(d): arr.append(arr.pop(0))

print(arr)

`