Python Program to left shift elements in an array


December 16, 2022, Learn eTutorial
1299

What is the left shift or left rotate array?

An array in python is a set of elements of the same type indexed by a common variable. Array elements are stored in the sequential list as array[0]= the first element, array[1] = second, like that. In this simple python program, we need left rotate the elements of the array n times.

For example, consider that array A contains elements 1,2,3,4,5 Arr A = [ 1, 2, 3, 4, 5 ] So we assume we want to rotate the elements by two times left.

  • In the first rotation, the array will be like this A = [2, 3, 4, 5, 1]
  • after the second rotation, the array will be changed to A =[3, 4, 5, 1, 2]

like this, we can rotate any number of times.

How to left shift an array in python?

Let us take the left shift logic in the python program, we open a for loop, then save the array's first element into a variable. Open inner for loop to left-shift the elements by one and append the last element from the saved variable. The outer for loop will continue until the number of times we need to left rotate the elements.

ALGORITHM

STEP 1: Initialize an array using some elements. And assign a value to n as the number of times we want to left rotate.

STEP 2: Now we display the original array using a for loop  in python programming.

STEP 3: Open the outer for loop till the number n from zero using the range method.

STEP 4: Store the first element arr[i] to a variable.

STEP 5: Open the inner loop to traverse from the first element to the length of the array minus one. We have to use less than one to append the last element from the variable.

STEP 6: Apply the left shift in python program by using the method arr[j] = arr[j+1] and it will change the first element as the second element.

STEP 7: Append the last element from the variable we stored as the first element.

STEP 8: Use a for loop and print statement print the result.


To left shift array elements using the python program, we are using the below concepts, we recommend learning those for a better understanding

Python Source Code

                                          arr = [1, 2, 3, 4, 5];     
    
n = 1;    # how many times array should be shifted
   
print("Original array: ");    
for i in range(0, len(arr)):    # displaying the first or real array
    print(arr[i]),     
     
for i in range(0, n):    # rotate the element of array using for loop 
    
    first = arr[0];    # saving the first element to a variable
        
    for j in range(0, len(arr)-1):    
       
        arr[j] = arr[j+1];    #shifting to left by one             
  
    arr[len(arr)-1] = first;    # adding the first element to array from the variable
     
print();    
     

print("Array after left rotation: ");    
for i in range(0, len(arr)):    
    print(arr[i]),    
                                      

OUTPUT

Original array: 
1
2
3
4
5

Array after left rotation: 
2
3
4
5
1