Lesson guide
What this Python exercise practices
Rotate List by N Positions is a intermediate practice lesson that focuses on loops, iteration, counters. It is designed to be solved in about 15 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Lists or strings
- Basic for loop syntax
Difficulty and time
- Level
- Intermediate
- Estimated time
- 15 minutes
Practice path
Summary
Rotate a list by n positions. Positive n rotates to the right, negative n rotates to the left.
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]
Explanation
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 input 0
rotate_list([1, 2, 3], -1)
Sample output 0
[2, 3, 1]
Explanation 0
Negative n rotates left by 1.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.