Slicing: rotate right by k
Read the task → edit your code → Run to see the output → Run tests to check your answer.
Slicing carves out part of a list with list[start:stop]. Two slices can
be glued back together with +:
nums = [1, 2, 3, 4, 5]
nums[3:] # [4, 5] — from index 3 to the end
nums[:3] # [1, 2, 3] — up to (not including) index 3
nums[3:] + nums[:3] # [4, 5, 1, 2, 3]
Rotating a list right by k means the last k items wrap around to the
front. Note the slice point is len(nums) - k.
Your task
Write rotate(nums, k) that returns a new list rotated right by k.
Handle a k larger than the length (use k % len) and the empty list.
rotate([1, 2, 3, 4, 5], 2) # [4, 5, 1, 2, 3]
rotate([1, 2, 3], 4) # [3, 1, 2] — 4 % 3 == 1
rotate([], 3) # []
Hint: first shrink k with the modulo operator so a k bigger than the list
wraps around (guard the empty list before that, or % 0 blows up). Then picture
the result as two slices — the last k items and everything before them —
swapped front to back.
Tests
- rotate by 2
- k larger than len
- empty list
- k is zero
✦ Need help with this task?
Sign in or create a free account to get AI help. Free includes a monthly AI allowance.
$ Console output will appear here.