Syntax error Python program to right rotate the elements of an array

Python program to right rotate the elements of an array



When it is required to right rotate the elements of a list, the elements are iterated over, and a last element is assigned a value, after which the elements are iterated over, and an element is swapped.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [31, 42, 13, 34, 85, 0, 99, 1, 3]
n = 3
print("The value of n has been initialized to")
print(n)
print("The list is :")
print(my_list)

print("List is being right rotated by 3 elements...")
for i in range(0, n):
   last_elem = my_list[len(my_list)-1]

   for j in range(len(my_list)-1, -1, -1):
      my_list[j] = my_list[j-1]

   my_list[0] = last_elem

print()

print("List after right rotation is : ")
for i in range(0, len(my_list)):
   print(my_list[i])

Output

The value of n has been initialized to
3
The list is :
[31, 42, 13, 34, 85, 0, 99, 1, 3]
List is being right rotated by 3 elements...
List after right rotation is :
99
1
3
31
42
13
34
85
0

Explanation

  • A list is defined, and is displayed on the console.

  • The value of n is defined and is displayed on the console.

  • The list is iterated over, and the last element is assigned a value.

  • The list is iterated over again, and the step size is defined as -1, and it is specified to go till the last element of the list.

  • The last element is assigned to the first position of the list.

  • The list would have been rotated by three positions.

  • This is displayed as output on the console.

Updated on: 2021-04-16T11:58:06+05:30

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements