How to shift (rotate) items in a list with python ?

Created August 30, 2022 | Viewed 291 | by Benjamin Edit


Examples of how to rotate items in a list with python:

Create a list

mylist = [1,2,3,4,5,6,7]

Rotate values in a list

To shift values in a list, a solution is to use deque

from collections import deque

create a new deque object

items_obj = deque(mylist)

For example, let's shift items by 2 to the right:

items_obj.rotate(2)

convert the object to a list:

new_list = list(items_obj)

gives

[6, 7, 1, 2, 3, 4, 5]

Another example, shift by 3 to the left:

items_obj = deque(mylist)

items_obj.rotate(-3)

new_list = list(items_obj)

new_list

gives the

[4, 5, 6, 7, 1, 2, 3]

References

Links Site
Shift Values in a List Using Python theprogrammingexpert.com
Efficient way to rotate a list in python stackoverflow