Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Rotate List by N Positions

Rotate a list by n positions. Positive n rotates to the right, negative n rotates to the left.

Python practice15 minLoops & IterationIntermediateLast updated March 15, 2026

Problem statement

Implement rotate_list(lst, n) that returns a new list which is the input list rotated by n positions. A positive n means rotate to the right; a negative n means rotate to the left. Rotation should wrap around and handle |n| larger than the list length. The original list must not be mutated.

Task

Practice index arithmetic, modular arithmetic, and handling edge cases like empty lists or n larger than list length.

Examples

Right rotation

Input

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

Output

[4, 5, 1, 2, 3]

Each element moves two positions to the right; the last two wrap to the front.

Input format

Two arguments: lst (a list) and n (an integer).

Output format

A new list rotated by n positions.

Constraints

Do not use external libraries. Aim for O(n) time and O(n) extra space for the returned list. The input list may be empty.

Samples

Sample 1

Input

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

Output

[2, 3, 1]

Negative n rotates left by 1.