Exercise · Lists · lesson 11 of 11
Exercise: rotate a list
Write a function rotate(nums, k) that returns a new list—the elements of nums shifted right by k positions. An element that goes past the right end moves to the start of the list. The function does not change the list nums itself.
rotate([1, 2, 3, 4, 5], 2)→[4, 5, 1, 2, 3]rotate([1, 2, 3], 4)→[3, 1, 2]rotate([], 3)→[]
Constraints: nums holds from 0 to 1000 elements; k is from 0 to 1000 and may be greater than the length of the list—a shift by len(nums) positions puts the elements back in their places; for an empty list the result is an empty list; after the call, nums holds the same elements in the same order.
Do not add extra imports unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.