Python program to right rotate a list by n

PythonProgrammingServer Side Programming

Given a user input list and given the rotation number. Our task is to rotate the list from the given rotation number.

Example

Input A= [2, 4, 5, 12, 90]
rotation number=3
Output [ 90,12,2, 4, 5]

Method1

Here we traverse each element in the list and insert the element at required places in the second list.

Example

def right_rotation(my_list, num): 
   output_list = []
   for item in range(len(my_list) - num, len(my_list)):
      output_list.append(my_list[item])
   for item in range(0, len(my_list) - num):
      output_list.append(my_list[item])
   return output_list
# Driver Code
A=list()
n=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n)):
   p=int(input("n="))
   A.append(int(p))
   print (A)
rot_num=int(input("Enter rotate number"))
print("After rotation",right_rotation(A, rot_num))
python54.py

Output

Enter the size of the List 6
Enter the number
n= 11
[11]
n= 22
[11, 22]
n= 33
[11, 22, 33]
n= 44
[11, 22, 33, 44]
n= 55
[11, 22, 33, 44, 55]
n= 66
[11, 22, 33, 44, 55, 66]
Enter rotate number 3
After rotation [44, 55, 66, 11, 22, 33]

Method2

Here we apply slicing technique using len().

A=list()
ni=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(ni)):
   p=int(input("ni="))
   A.append(int(p))
   print (A)
n = 3
A = (A[len(A) - n:len(A)] + A[0:len(A) - n])
print("After Rotation",A)

Output

Enter the size of the List 6
Enter the number
ni= 11
[11]
ni= 22
[11, 22]
ni= 33
[11, 22, 33]
ni= 44
[11, 22, 33, 44]
ni= 55
[11, 22, 33, 44, 55]
ni= 66
[11, 22, 33, 44, 55, 66]
After Rotation [44, 55, 66, 11, 22, 33]

Method3

In this method, last n elements of the list A were taken and then remaining elements of the list A.

Example

A=list()
ni=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(ni)):
   p=int(input("ni="))
   A.append(int(p))
   print (A)
n = 3
A = (A[-n:] + A[:-n])
print("After Rotation",A)

Output

Enter the size of the List 6
Enter the number
ni= 11
[11]
ni= 22
[11, 22]
ni= 33
[11, 22, 33]
ni= 44
[11, 22, 33, 44]
ni= 55
[11, 22, 33, 44, 55]
ni= 66
[11, 22, 33, 44, 55, 66]
After Rotation [44, 55, 66, 11, 22, 33]
raja
Published on 22-Nov-2018 05:31:54
Advertisements