Python program to right rotate a list by n

ProgrammingPythonServer Side Programming

In this article, we will see how to right rotate a list from the given rotation number. A list has comma-separated values (items) between square brackets. Important thing about a list is that the items in a list need not be of the same type

Let’s say the following is our input list −

myList = [5, 20, 34, 67, 89, 94, 98, 110]

The following is the output with n = 4 −

89, 94, 98, 110, 5, 20, 34, 67

Right rotate a list by n using slicing

Here, slicing is used to right rotate a list −

Example

# Create a List myList =[5, 20, 34, 67, 89, 94, 98, 110] print("List before rotation = ",myList) # The value of n for rotation position n = 4 # Rotating the List myList = (myList[len(myList) - n:len(myList)] + myList[0:len(myList) - n]) # Display the Update List after rotation print("Updated List after rotation = ",myList)

Output

List before rotation =  [5, 20, 34, 67, 89, 94, 98, 110]
Updated List after rotation =  [89, 94, 98, 110, 5, 20, 34, 67]

Right Rotate a List by n with if

Here, the if statement is used to right rotate a list −

Example

# Create a List myList =[5, 20, 34, 67, 89, 94, 98, 110] print("List before rotation = ",myList) # The value of n for rotation position n = 4 # Rotating the List if n>len(myList): n = int(n%len(myList)) myList = (myList[-n:] + myList[:-n]) # Display the Update List after rotation print("Updated List after rotation = ",myList)

Output

List before rotation =  [5, 20, 34, 67, 89, 94, 98, 110]
Updated List after rotation =  [89, 94, 98, 110, 5, 20, 34, 67]

Right Rotate a List by n with for loop

Here, the for loop is used to right rotate a list −

Example

# The value of n for rotation position num = 4 # Create a List myList =[5, 20, 34, 67, 89, 94, 98, 110] print("List before rotation = ",myList) newlist = [] for item in range(len(myList) - num, len(myList)): newlist.append(myList[item]) for item in range(0, len(myList) - num): newlist.append(myList[item]) # Display the Update List after rotation print("Updated List after rotation = ",newlist)

Output

List before rotation =  [5, 20, 34, 67, 89, 94, 98, 110]
Updated List after rotation =  [89, 94, 98, 110, 5, 20, 34, 67]
raja
Updated on 11-Aug-2022 11:29:49

Advertisements