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

Published: August 30, 2022

Updated: December 09, 2022

Tags: Python; List;

DMCA.com Protection Status

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]