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
Use a function assuming n
is the shift that is less than the length of list l
like so:
shift = lambda l, n: l[-n:] + l[:-n] # i.e. shift([1, 2, 3, 4], 3)
If you are trying to shift the elements, use collections.deque rotate method:
#! /usr/bin/python3
from collections import deque
a = deque([1, 2, 3, 4])
a.rotate()
print(a)
Result:
[2, 3, 4, 1]
You can use this:
li=li[-1:]+li[:-1]
you can use roll function from numpy.
>>> import numpy as np
>>> q = [1, 2, 3, 4, 5]
>>> np.roll(q, 2)
array([4, 5, 1, 2, 3])
Hope it helps!
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.
Solution for your query :
def shift(aList):
l = list()
n = len(aList)
l.append(aList[-1])
temp = aList[:n-1]
for i in temp:
l.append(i)
return l
print(shift(aList=[1,2,3]))