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:


convert the object to a list:

new_list = list(items_obj)


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

Another example, shift by 3 to the left:

items_obj = deque(mylist)


new_list = list(items_obj)


gives the

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


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