Perform left rotation by two positions in Array Using Python

In this programming tutorial, we will learn to write a Python program to perform a left rotation of array elements by two positions.

For Example:

Suppose we have an array arr = [1, 2, 3, 4, 5],

So after two rotation array will become arr = [3, 4, 5, 1, 2]

There are multiple ways to write this program in Python. We will see one by one.

Program 1: Using pop() and append()

With the help of pop() and append() methods of Python, we can perform a left rotation of array elements by two positions. We can remove the first two elements of the array using the pop() method and then append them to the end of the array using the append() method. Below is the program.

arr = [1, 2, 3, 4, 5]
arr.append(arr.pop(0))
arr.append(arr.pop(0))
print("After two left rotaion :",arr)

Output:

After two left rotaion : [3, 4, 5, 1, 2]

Program 2: Using Slicing in Python

With the help of slicing in Python, you can perform left rotation in two positions. You have to create two slices of the array, one starting from index 2 to the end and the other starting from index 0 to index 2, and then concatenate them. Below is the program

arr = [1, 2, 3, 4, 5]
arr = arr[2:] + arr[:2]
print("After two left rotaion :",arr)

Output:

After two left rotaion : [3, 4, 5, 1, 2]

Program 3: Using the For loop in Python

With the help of for loop in Python, you can perform a left rotation of array elements by two positions. We will iterate over the array and move each element to the left by two positions. Below is the program.

arr = [1, 2, 3, 4, 5]
for i in range(2):
    temp = arr[0]
    for j in range(len(arr)-1):
        arr[j] = arr[j+1]
    arr[-1] = temp
print("After two left rotaion :",arr)

Output:

After two left rotaion : [3, 4, 5, 1, 2]

Conclusion:

In this post, we have learned various ways to write a program to perform the left rotation of array elements by two positions. Various approaches are like slicing, pop() and append() methods, and for loop to achieve this. Hope this tutorial is helpful to you in understanding Python Program.