Home / Python / Example programs / Lists

Python program: Rotate a list

Move items from the end of a list to the front.

The code

def rotate(items, k):
    k %= len(items)
    return items[-k:] + items[:-k]

xs = [1, 2, 3, 4, 5]
print(rotate(xs, 1), rotate(xs, 2), rotate(xs, 7))

from collections import deque
d = deque(xs)
d.rotate(2)
print(list(d))

Output

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

How it works

Two slices glued together. k %= len(items) makes rotating by 7 the same as by 2 for a 5-item list.

Python features used

Learn the ideas behind it in the free lesson Lists & Tuples.