PythonMastery
Python programs · Lists · beginner

Rotate a list in Python

Rotate a list left or right by k places in Python with slicing, handle k larger than the list, and use collections.deque.rotate().

To rotate a list left by 2 places, move the first 2 items to the end: [1, 2, 3, 4, 5] becomes [3, 4, 5, 1, 2].

The program

python
def rotate_left(items, k):
    if not items:
        return []
    k = k % len(items)
    return items[k:] + items[:k]

numbers = [1, 2, 3, 4, 5]

print(rotate_left(numbers, 2))
print(rotate_left(numbers, 7))
print(rotate_left(numbers, -1))
print(numbers)
output
[3, 4, 5, 1, 2]
[3, 4, 5, 1, 2]
[5, 1, 2, 3, 4]
[1, 2, 3, 4, 5]

How it works

Another way: deque.rotate()

A deque from the collections module has a rotate() method. It changes the deque in place, and a positive number rotates to the right:

python
from collections import deque

d = deque([1, 2, 3, 4, 5])
d.rotate(2)
print(list(d))
d.rotate(-2)
print(list(d))
output
[4, 5, 1, 2, 3]
[1, 2, 3, 4, 5]

Learn the idea: Lists & Sequences, Functions & Scoping, collections: The Stdlib's Hidden Power