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
If you actually want to shift the elements, you can use modulo to cycle the list and reassign the elements to their shifted positions:
def shift(lst, shft=0):
ln = len(lst)
for i, ele in enumerate(lst[:]):
lst[(i + shft) % ln] = ele
return lst
In [3]: shift( ['a','b','c','d'] , 1)
Out[3]: ['d', 'a', 'b', 'c']
In [4]: shift( ['a','b','c','d'] , 2)
Out[4]: ['c', 'd', 'a', 'b']
In [5]: shift( ['a','b','c','d'] , 3)
Out[5]: ['b', 'c', 'd', 'a']
If you only want a single shift just shift the last element to the front extending the list:
def shift(lst):
lst[0:1] = [lst.pop(),lst[0]]
return lst
Both of which change the original list.