 # getting rotation of a list in python

• Last Update :
• Techknowledgy :

These are five easy methods to rotate a given list in Python.,In this article, we will learn how to rotate a list in Python. List rotation is an easy technique and it also comes quite handy to programmers. Let us discuss some ways in which we can achieve rotation.,In this method, we change the indexing of a list by reassigning a new index to each element after rotation. In the example below, the list is rotated by 3 in which new index values are assigned., Copy a list to another so that it does not change values when I modify the first list in Python

This is the most basic method for rotating a list in Python.
As the name suggests, we traverse the list one by one. Then we put the element in its place. The example below shows this technique. We rotate the list by an integer n, which in this case is 3.
Time complexity: O(n)

```def right_rotate(lists, n):
output_list = []
x = len(lists)

for item in range(x - n, x):
output_list.append(lists[item])

for item in range(0, x - n):
output_list.append(lists[item])

return output_list

rotate_num = 3
list_1 = [10, 25, 36, 43, 52, 60]
print("List:", list_1)
print("Rotated list: ", right_rotate(list_1, rotate_num))```

Output:

```List: [10, 25, 36, 43, 52, 60]
Rotated list: [43, 52, 60, 10, 25, 36]```

Slicing is another way to achieve rotation of a list. This is done by using the len() function.
In the example below, the list is sliced. The value of n, in this case, is 3 i.e. the number of slices. Therefore the list is rotated likewise.

```n = 3

list_1 = [11, 22, 33, 44, 55]
print("List:", list_1)

list_1 = (list_1[len(list_1) - n: len(list_1)] +
list_1[0: len(list_1) - n])
print("Rotated list:", list_1)```

In this method, we change the indexing of a list by reassigning a new index to each element after rotation.
In the example below, the list is rotated by 3 in which new index values are assigned.

```list_1 = [1, 4, 6, 7, 2]

# printing original list
print("List : " + str(list_1))

list_1 = [list_1[(i + 3) % len(list_1)]
for i, x in enumerate(list_1)
]

print("Rotated list : " + str(list_1))```

In Python, there exists a collection module that contains a deque class. This class has an inbuilt rotate() function.
In the example below, we have used the inbuilt function rotate().

```from collections
import deque

list_1 = [11, 22, 33, 44, 55]
print("List : " + str(list_1))

list_1 = deque(list_1)
list_1.rotate(-3)
list_1 = list(list_1)

print("Rotated List: " + str(list_1))```

Suggestion : 2

Last Updated : 30 Nov, 2018

```Original list: [1, 4, 6, 7, 2]
List after left rotate by 3: [7, 2, 1, 4, 6]
List after right rotate by 3(back to original): [1, 4, 6, 7, 2]```

```Original list: [1, 4, 6, 7, 2]
List after left rotate by 3: [7, 2, 1, 4, 6]
List after right rotate by 3(back to original): [1, 4, 6, 7, 2]```

Suggestion : 3

Python's Numpy module provides a built-in roll() function to carry out the rotation on an array. Firstly, it creates an array by passing a range (starting value, last value(excluded)) using numpy.arange() function. Then, the array and the number of rotations are passed as arguments to numpy.roll() function.,In this article, we will learn to rotate a list in Python. We will use some built-in functions, simple approaches, and some custom codes as well. Let's first have a quick look over what is a list in Python.,This method imports deque from the collections module of Python. deque() class provides rotate() function to perform List Rotation. This is also an efficient way to rotate a list as it is faster than the slicing technique. It is optimized for pulling and pushing on both ends.,This method increases the Space Complexity of the program. This method creates an empty list and stores the modified list into a new list. It works similar to list comprehension. It iterates the first list one by one and then places the elements at suitable positions in a second list using the append() function.

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values.

```list1 = ["Ram", "Arun", "Kiran"]
list2 = [16, 78, 32, 67]
list3 = ["apple", "mango", 16, "cherry", 3.4]```

This method simply rotates a list in a one-liner code. This is the most generic and efficient method to achieve rotation of a list. It performs a slicing operation by taking the number of rotations. In this case, it rotates the list l1, 3 spaces to the right and left side. It joins the latter sliced part of the list with the initial sliced part of the list. You can provide any number of rotations according to the need.

```#input list
l1 = [1, 4, 6, 7, 2]
print("Original List : " + str(l1))

#left rotate by 3
l1 = l1[3: ] + l1[: 3]
print("Left rotation of List by 3 : " + str(l1))

#right rotate by 3
l1 = l1[-3: ] + l1[: -3]
print("Right rotation of List by 3 : " + str(l1))```

This method is performed in one line using List Comprehension. In this method, we just reassign the index to each value to a specific position after rotation. Just replace 3 with any number of rotation you want.

```#input list
l1 = [1, 4, 6, 7, 2]
print("Original List : " + str(l1))

#left rotate by 3
l1 = [l1[(i + 3) % len(l1)]
for i, x in enumerate(l1)
]
print("Left rotation of List by 3 : " + str(l1))

#right rotate by 3
l1 = [l1[(i - 3) % len(l1)]
for i, x in enumerate(l1)
]
print("Right rotation of List by 3 : " + str(l1))```

This method increases the Space Complexity of the program. This method creates an empty list and stores the modified list into a new list. It works similar to list comprehension. It iterates the first list one by one and then places the elements at suitable positions in a second list using the `append()` function.

```#number of rotations
num = 3
l1 = [1, 2, 3, 4, 5, 6]
l2 = []

# Will add values from n to the new list
for ele in range(len(l1) - num, len(l1)):
l2.append(l1[ele])
# Will add the values before n to the end of new list
for ele in range(0, len(l1) - num):
l2.append(l1[ele])

print("Right rotation of List by 3 : " + str(l2))```

This method also involves the Slicing technique but along with `len()` function.

```#number of rotations
num = 3

#input list
l1 = [1, 2, 3, 4, 5, 6]

l1 = (l1[len(l1) - num: len(l1)] + l1[0: len(l1) - num])

print("Right rotation of List by 3 : " + str(l1))```

Suggestion : 4
1._
```def rotate(l, n):
return l[-n: ] + l[: -n]```

More conventional direction:

```def rotate(l, n):
return l[n: ] + l[: n]```

Example:

```example_list = [1, 2, 3, 4, 5]

rotate(example_list, 2)
#[3, 4, 5, 1, 2]```

If applicable, you could use `collections.deque` as a solution:

```import collections

d = collections.deque([1, 2, 3, 4, 5])
d.rotate(3)

print d
>>>
deque([3, 4, 5, 1, 2])```

The following function will rotate the list `l`, `x` spaces to the right:

```def rotate(l, x):
return l[-x: ] + l[: -x]```

Note that this will only return the original list if `x` is outside the range `[-len(l), len(l)]`. To make it work for all values of `x`, use:

```def rotate(li, x):
return li[-x % len(li): ] + li[: -x % len(li)]```
1._
```>>> l = [1, 2, 3, 4] >>>
l[1: ] + l[: 1]
[2, 3, 4, 1] >>>
l = [1, 2, 3, 4] >>>
l[2: ] + l[: 2]
[3, 4, 1, 2] >>>
l[-1: ] + l[: -1]
[4, 1, 2, 3]```

A general rotate `n` to the left (positive y in the call to `rotate`) or right (negative y) then:

```def rotate(l, y = 1):
if len(l) == 0:
return l
y = y % len(l) # Why ? this works
for negative y

return l[y: ] + l[: y]```

If you want the direction of rotation to be the same as your example, just negate `y` in rotate.

```def rotate(l, y = 1):
if len(l) == 0:
return l
y = -y % len(l) # flip rotation direction

return l[y: ] + l[: y]```

Suggestion : 5

February 18, 2022 2 Comments,June 17, 2022 at 5:56 am,June 17, 2022 at 12:44 pm

1._
```lst = [0, 1, 2, 3]

#rotated backwards(to left)
lst.append(lst.pop(0))
print(lst)

lst = [0, 1, 2, 3]

#rotated forward(to right)
lst.insert(0, lst.pop())
print(lst)

#Output: [1, 2, 3, 0]
[3, 0, 1, 2]```

You can also use the deque() data structure from the Python collections module to rotate a list.

```from collections
import deque

items = deque([0, 1, 2, 3])

#rotated backwards(to left)
items.rotate(-1)

print(items)

items = deque([0, 1, 2, 3])

#rotated forward(to right)
items.rotate(1)

print(items)

#Output:
deque([1, 2, 3, 0])
deque([3, 0, 1, 2])```
3._
```lst = [0, 1, 2, 3]

list_rotated_backwards = lst[1: ] + lst[: 1]
list_rotated_forward = lst[-1: ] + lst[: -1]

print(list_rotated_backwards)
print(list_rotated_forward)

#Output: [1, 2, 3, 0]
[3, 0, 1, 2]```

Below is a function which will rotate values in a list multiple times to the left or right depending on the argument values passed.

```def rotateList(lst, direction, n):
if direction == "backwards":
for i in range(0, n):
lst.append(lst.pop(0))
else:
for i in range(0, n):
lst.insert(0, lst.pop())
return lst

print(rotateList([0, 1, 2, 3, 4, 5, 6], "backwards", 2))
print(rotateList([0, 1, 2, 3, 4, 5, 6], "forwards", 3))

#Output: [2, 3, 4, 5, 6, 0, 1]
[4, 5, 6, 0, 1, 2, 3]```

Below are some examples of how to rotate items in a list with the deque rotate() function.

```from collections
import deque

items = deque([0, 1, 2, 3])

#rotated backwards(to left)
items.rotate(-1)

print(items)

items = deque([0, 1, 2, 3])

#rotated forward(to right)
items.rotate(1)

print(items)

#Output:
deque([1, 2, 3, 0])
deque([3, 0, 1, 2])```

When I try lst[:-k] + lst[-k:], I’m just getting back the original list.

```lst = [0, 1, 2, 3]

list_rotated_backwards = lst[1: ] + lst[: 1]
proposed_method = lst[: -1] + lst[-1: ]

print(list_rotated_backwards)
print(proposed_method)

#Output: [1, 2, 3, 0]
[0, 1, 2, 3]```

Suggestion : 6

This is the simplest way to rotate a list in Python. We go through the list one by one, as the name implies. The element is then placed in its proper position.,We modify the indexing of a list in this approach by reassigning a new index to each element after rotation. In the following example, the list is rotated by one time, and new index values are assigned.,Another method for rotating a list is slicing. The len() method is used to do this. The list is sliced in the following example.,In this situation, the value of n_splits is 1, indicating the number of slices. As a result, the list is cycled in the same manner.

```# Define the list
list_1 = [1, 2, 3, 4, 5]
print("Original list:", list_1)
# Set the number of splits
n_splits = 1
# Rotate The List
list_1 = (list_1[len(list_1) - n_splits: len(list_1)] + list_1[0: len(list_1) - n_splits])
print("Rotated list:", list_1)```
```Original list: [1, 2, 3, 4, 5]
Rotated list: [5, 1, 2, 3, 4]```
```def ROTATE(lists, n):
output_list = []
x = len(lists)
for item in range(x - n, x):
output_list.append(lists[item])
for item in range(0, x - n):
output_list.append(lists[item])
return output_list
rotate_num = 1
list_1 = [1, 2, 3, 4, 5]
print("Original List:", list_1)
print("Rotated list: ", ROTATE(list_1, rotate_num))```
```Original List: [1, 2, 3, 4, 5]
Rotated list: [5, 1, 2, 3, 4]```
```list_1 = [1, 2, 3, 4, 5]
print("Original List : " + str(list_1))
list_1 = [list_1[(i + 4) % len(list_1)]
for i, x in enumerate(list_1)
]
print("Rotated list : " + str(list_1))```
```Original List: [1, 2, 3, 4, 5]
Rotated list: [5, 1, 2, 3, 4]```

Suggestion : 7

Here, slicing is used to right rotate a list −,Here, the if statement is used to right rotate a list −,Here, the for loop is used to right rotate a list −,Program to reverse a list by list slicing in Python

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`

### 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)```