Drill

ProblemsPython › warmup

Rotate a list

mediumwarmupPython

A carousel shows the same items starting from a different one each time it advances.

rotate_left(values: list<int>, by: int) → list<int>

Solve it in the editor →

Where you start

def rotate_left(values: list[int], by: int) -> list[int]:
    

Worked examples

CallResult
rotate_left([1, 2, 3, 4], 1)[2, 3, 4, 1]
rotate_left([1, 2, 3, 4], 5)[2, 3, 4, 1]
rotate_left([1, 2, 3, 4], -1)[4, 1, 2, 3]
rotate_left([1, 2, 3], 0)[1, 2, 3]

Hint

Reduce the shift with a modulo first, and remember that the modulo of a negative number is negative in most of these languages.

Reference solution in Python
def rotate_left(values: list[int], by: int) -> list[int]:
    n = len(values)
    if n == 0:
        return []
    k = by % n
    return values[k:] + values[:k]

The same problem in another language

More warmup problems in Python