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
items[k:]is everything from positionkto the end, anditems[:k]is the firstkitems. Joining them in that order gives the rotated list.- Rotating a list of 5 items by 5 places gives the same list again. So
k % len(items)removes the full turns: rotating by 7 is the same as rotating by 2. - With a negative
k,%gives a positive number in Python:-1 % 5is 4. Rotating left by 4 is the same as rotating right by 1. - The function builds a new list, so
numbersdoes not change. - The empty-list check stops
% 0, which would raise aZeroDivisionError.
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]