I want to rotate elements in a list, e.g. - shift the list elements to the right so [\'a\',\'b\',\'c\',\'d\'] would become [\'d\',\'a\',\'b\',\'c\'], o
Simple use of slice syntax:
def shift(seq):
return [seq[-1]] + seq[:-1]
assert shift([1, 2, 3, 4, 5]) == [5, 1, 2, 3, 4]
Generalized version with changeable shift:
def shift(seq, shift=1):
return seq[-shift:] + seq[:-shift]
assert shift([1, 2, 3, 4, 5]) == [5, 1, 2, 3, 4]
assert shift([1, 2, 3, 4, 5], 2) == [4, 5, 1, 2, 3]