Open In App

# Python | Ways to rotate a list

The rotation of a list has been discussed earlier also, but this particular article focuses on shorthands and various short techniques to achieve this in one-liners or one word. This operation is quite essential in a programmer’s life to achieve various tasks. Let’s discuss different ways we can rotate a list in Python

### Method 1: Rotate a list using Slicing

This particular method is the generic method and is mostly employed to achieve this task and has also been discussed in many articles as well. It works by just joining the later sliced part to the initial sliced part given the rotation number.

## Python3

 `# initializing list``test_list ``=` `[``1``, ``4``, ``6``, ``7``, ``2``]` `# printing original list``print` `(``"Original list : "` `+` `str``(test_list))` `# using slicing to left rotate by 3``test_list ``=` `test_list[``3``:] ``+` `test_list[:``3``]` `# Printing list after left rotate``print` `(``"List after left rotate by 3 : "` `+` `str``(test_list))` `# using slicing to right rotate by 3``# back to Original``test_list ``=` `test_list[``-``3``:] ``+` `test_list[:``-``3``]` `# Printing after right rotate``print` `(``"List after right rotate by 3(back to original) : "``                                        ``+` `str``(test_list))`

Output:

```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]```

### Method 2: Rotate a list using list Comprehension

This problem can also be solved by the naive method, but its shorter implementation would be with the help of list comprehension. In this method, we just reassign the index to each value to the specific position after rotation.

## Python3

 `# initializing list``test_list ``=` `[``1``, ``4``, ``6``, ``7``, ``2``]` `# printing original list``print` `(``"Original list : "` `+` `str``(test_list))` `# using list comprehension to left rotate by 3``test_list ``=` `[test_list[(i ``+` `3``) ``%` `len``(test_list)]``            ``for` `i, x ``in` `enumerate``(test_list)]` `# Printing list after left rotate``print` `(``"List after left rotate by 3 : "` `+` `str``(test_list))` `# using list comprehension to right rotate by 3``# back to Original``test_list ``=` `[test_list[(i ``-` `3``) ``%` `len``(test_list)]``            ``for` `i, x ``in` `enumerate``(test_list)]` `# Printing after right rotate``print` `(``"List after right rotate by 3(back to original) : "``                                        ``+` `str``(test_list))`

Output:

```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]```

### Method 3: Rotate a list using collections.deque.rotate()

The collections module has a deque class that provides the rotate(), which is an inbuilt function to allow rotation. This is a lesser-known function but has a greater utility.

## Python3

 `from` `collections ``import` `deque` `# initializing list``test_list ``=` `[``1``, ``4``, ``6``, ``7``, ``2``]` `# printing original list``print` `(``"Original list : "` `+` `str``(test_list))` `# using rotate() to left rotate by 3``test_list ``=` `deque(test_list)``test_list.rotate(``-``3``)``test_list ``=` `list``(test_list)` `# Printing list after left rotate``print` `(``"List after left rotate by 3 : "` `+` `str``(test_list))` `# using rotate() to right rotate by 3``# back to Original``test_list ``=` `deque(test_list)``test_list.rotate(``3``)``test_list ``=` `list``(test_list)` `# Printing after right rotate``print` `(``"List after right rotate by 3(back to original) : "``                                        ``+` `str``(test_list))`

Output:

```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]```

### Method 4: Rotate a list using Numpy

In this method, we will use Numpy.roll module to roll the list at a given position, i.e. we are rolling the list at position index 1.

## Python3

 `import` `numpy as np` `if` `__name__ ``=``=` `'__main__'``:` `    ``nums ``=` `[``11``, ``4``, ``6``, ``7``, ``8``, ``33``]``    ``k ``=` `1` `    ``x ``=` `np.roll(nums, k)``    ``print``(x)`

Output:

`[33 11  4  6  7  8]`

#### Method 5: Using a loop and pop() method

This method uses a loop to rotate the list lst by n positions.

## Python3

 `def` `rotate_list(lst, n):``    ``# Loop through the range of n positions to rotate``    ``for` `i ``in` `range``(n):``        ``# Remove the last element of the list and insert it at the beginning``        ``lst.insert(``0``, lst.pop())``    ``# Return the rotated list``    ``return` `lst` `# Example usage:``my_list ``=` `[``1``, ``2``, ``3``, ``4``, ``5``]``rotated_list ``=` `rotate_list(my_list, ``2``)``print``(rotated_list) `

Output

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

Time complexity: O(n)

Auxiliary space: O(1)

Method 6: Using deque.rotate()

Algorithm:

1. Import deque from the collections module.
2. Initialize the test_list.
3. Print the original list.
4. Create a deque object from the test_list.
5. Use the rotate function of deque to left rotate
Convert deque object back to a list.
6. Print the list after left rotation.
7. Create a deque object from the modified list.
8. Use the rotate function of deque to right rotate
9. Convert deque object back to a list.
10. Print the list after right rotation.

## Python3

 `from` `collections ``import` `deque` `# initializing list``test_list ``=` `[``1``, ``4``, ``6``, ``7``, ``2``]` `# printing original list``print` `(``"Original list : "` `+` `str``(test_list))` `# using deque.rotate() to left rotate by 3``test_deque ``=` `deque(test_list)``test_deque.rotate(``-``3``)``test_list ``=` `list``(test_deque)` `# Printing list after left rotate``print` `(``"List after left rotate by 3 : "` `+` `str``(test_list))` `# using deque.rotate() to right rotate by 3``# back to Original``test_deque ``=` `deque(test_list)``test_deque.rotate(``3``)``test_list ``=` `list``(test_deque)` `# Printing after right rotate``print` `(``"List after right rotate by 3(back to original) : "``                                        ``+` `str``(test_list))`

Output

```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]```

Time Complexity:

The time complexity of the algorithm using deque is O(n) as we are performing the deque.rotate() method operation only once for left and right rotations.

Auxiliary Space:

The auxiliary space complexity of the algorithm using deque is O(n) as we are converting the deque object back to the list using list() method.

Method 7 : Using reversed() and slicing:

Algorithm:

1.Define a function called rotate_list that takes two arguments: lst, which is a list of integers, and n, which is the number of positions to rotate the list to the left.
2.Use list slicing to extract the last n elements of the list lst and reverse the order of these elements using the reversed() function. Convert the reversed sublist back to a list using the list() function.
3.Use list slicing again to extract the elements of the original list lst that come before the last n elements, and concatenate this sublist with the reversed sublist using the + operator.
4.Return the concatenated list as the result of the function.
5.Define a list called my_list containing the integers 1 through 5.
6.Call the rotate_list function with my_list and the argument 2, and assign the result to a variable called rotated_list.
7.Print the value of rotated_list to the console.

Regenerate response

## Python3

 `def` `rotate_list(lst, n):``    ``return` `list``(``reversed``(lst[``-``n:])) ``+` `lst[:``-``n]` `my_list ``=` `[``1``, ``2``, ``3``, ``4``, ``5``]``# printing original list``print` `(``"Original list : "` `+` `str``(my_list))`` ` `rotated_list ``=` `rotate_list(my_list, ``2``)``print``(rotated_list)``#This code is contributed by Jyothi pinjala`

Output

```Original list : [1, 2, 3, 4, 5]
[5, 4, 1, 2, 3]```

Time complexity: O(n)

The time complexity of the algorithm is O(n) because we need to reverse a sublist of size n and concatenate two sublists of sizes n-k and k, where k is the number of elements to be rotated. These operations take constant time for each element, so the total time complexity is proportional to the size of the input list.

Space complexity: O(n)

The space complexity of the algorithm is also O(n) because we create a new list of size n to store the rotated elements. The original list is not modified in place.

Method 8 : Using numpy concatenate():

1. Define two functions rotate_left and rotate_right which take an array and the number of places to rotate.
2. Use numpy concatenate() function to join the sliced array after and before the n-th index of the input array to get the rotated array.
3. In rotate_left(), concatenate the array slice from the nth index to the end of the array with the array slice from the beginning of the array to the (n-1)th index.
4. In rotate_right(), concatenate the array slice from the (n-1)th index to the end of the array with the array slice from the beginning of the array to the nth index.
5. Return the rotated array.
6. Call the rotate_left() and rotate_right() functions to rotate the input array and print the output.

## Python3

 `import` `numpy as np` `def` `rotate_left(arr, n):``    ``return` `np.concatenate((arr[n:], arr[:n]))` `def` `rotate_right(arr, n):``    ``return` `np.concatenate((arr[``-``n:], arr[:``-``n]))` `# Example usage``original_list ``=` `[``1``, ``4``, ``6``, ``7``, ``2``]``print``(``"Original list:"``, original_list)` `rotated_left ``=` `rotate_left(original_list, ``3``)``print``(``"List after left rotate by 3:"``, rotated_left)` `rotated_right ``=` `rotate_right(rotated_left, ``3``)``print``(``"List after right rotate by 3 (back to original):"``, rotated_right)`

Output:

```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]```

Time Complexity:
The time complexity of both the rotate_left() and rotate_right() functions is O(n), where n is the length of the input array. The concatenate() function has a time complexity of O(n), and it is called twice in each function.

Space Complexity:
The space complexity of both the rotate_left() and rotate_right() functions is O(n), where n is the length of the input array.