Lesson guide
What this Python exercise practices
Rotate a list by k positions is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 19 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 19 minutes
Practice path
Summary
Rotate elements of a list to the right by k positions (negative k rotates left).
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]
Explanation
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 input 0
rotate_list([1,2,3,4], -1)
Sample output 0
[2, 3, 4, 1]
Explanation 0
Negative k 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.