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
You can use negative indices together with list concatenation:
def shift(seq, n=0):
a = n % len(seq)
return seq[-a:] + seq[:-a]
The question seems to imply to me that the list itself should be modified rather than a new list created. A simple in place algorithm is therefore:
lst = [1, 2, 3, 4, 5]
e1 = lst[-1]
for i, e2 in enumerate(lst):
lst[i], e1 = e1, e2
print(lst)
Giving:
[5, 1, 2, 3, 4]
If you are allergic to slice notation: a.insert(0,a.pop())
Usage:
In [15]: z=[1,2,3]
In [16]: z.insert(0,z.pop())
In [17]: z
Out[17]: [3, 1, 2]
In [18]: z.insert(0,z.pop())
In [19]: z
Out[19]: [2, 3, 1]
This could be done simply by using list method: insert,
values = [2, 3, 5, 7, 11, 13]
def shift(list):
new_list = []
for i in list:
new_list.insert(len(new_list)-1, i)
return new_list
print(shift(values))
Output is:
[3, 5, 7, 11, 13, 2]
You can just slice the last element off the list, then add it to the beginning of a new list:
aList = [aList[-1]] + aList[:-1]
Here is the result:
>>> aList = [1,2,3]
>>> aList = [aList[-1]] + aList[:-1]
>>> aList
[3, 1, 2]
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]