Rotate a list
Write rotate(xs, k) that returns a new list rotated k steps to the right. k may be larger than the list, and the list may be empty.
rotate([1, 2, 3, 4, 5], 2) # [4, 5, 1, 2, 3]
rotate([1, 2, 3], 7) # [3, 1, 2]
rotate([], 4) # []
Show hint
Rotating by the list length changes nothing, so reduce k with %. Watch out for dividing by zero.
Show solution
def rotate(xs, k):
if not xs:
return []
k %= len(xs)
return xs[-k:] + xs[:-k]
The last k items move to the front. The empty check avoids k % 0. When k is 0, xs[-0:] is the whole list and xs[:-0] is empty, so the result is still correct.
Want a problem like this every day? See today's problem and keep a streak going.