Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Rotate a list by k positions

Rotate elements of a list to the right by k positions (negative k rotates left).

Python practice19 minLists & TuplesIntermediateLast updated March 17, 2026

Problem statement

Given a list and an integer k, return a new list where the elements have been rotated to the right by k positions. If k is negative, rotate to the left by abs(k). For example, rotating [1,2,3,4,5] by 2 yields [4,5,1,2,3]. Handle k values larger than the list length by using modulo. If the list is empty, return an empty list.

Task

Implement rotate_list(lst, k) that returns a new list rotated by k positions without mutating the original.

Examples

Rotate right by 2

Input

rotate_list([1,2,3,4,5], 2)

Output

[4, 5, 1, 2, 3]

Elements move two positions to the right.

Input format

A list (lst) and an integer k.

Output format

A new list rotated to the right by k positions (or left if k is negative).

Constraints

Do not mutate the input list. Work in O(n) time and O(n) extra space. Handle negative and large k values correctly.

Samples

Sample 1

Input

rotate_list([1,2,3,4], -1)

Output

[2, 3, 4, 1]

Negative k rotates left by 1.