Python Program for array rotation

In this article, we will learn to rotate an array using a python program. We will rotate the array from left, the first element of the array will shift to last and all the other elements come forward, this is the 1 rotation, and we make a program that rotates the array into n times.



Explanation

  1. First, we store the first element and then shift the other element by one.
  2. And then the first element will be add be to the last.
  3. Lastly, we print the new array.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# python program to rotate array 
# array
arr = [1, 2, 3, 4, 5] 

# number of time to rotate
n = 1

# print original array
print("Original array: ")
for i in range(0, len(arr)):    
    print(arr[i], end = " ")       
print()

# Start rotating the array
# itrate the loop from 0 to n
for i in range(0, n):    
    # the first element of array stored in first variable 
    first = arr[0]
    
    for j in range(0, len(arr)-1):    
        # shift all the other element of array by one    
        arr[j] = arr[j+1]
            
    # then first element of array will be added to the end    
    arr[len(arr)-1] = first  
     
     
# now, display the new array  
print("Array after rotation: ") 
for i in range(0, len(arr)):    
    print(arr[i],end =" ")    
print()

Output

Original array: 
1 2 3 4 5 
Array after rotation: 
2 3 4 5 1 
Next Post Previous Post
No Comment
Add Comment
comment url