Lesson·difficulty 2/5·~12 min
Slicing: rotate right by k
Slicing carves out part of a list with list[start:stop]. Two slices can
be glued back together with +:
python
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.
python
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
✦ Stuck? Ask for a spark
Sign in or create a free account to use your monthly AI explainer allowance.
warming up
Loading editor…
Consolewaiting
$ Console output will appear here.