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']
, or [1,2,3]
becomes [3,1,2]
.
I tried the following, but it's not working:
def shift(aList):
n = len(aList)
for i in range(len(aList)):
if aList[i] != aList[n-1]:
aList[i] = aList[i+1]
return aList
elif aList[i] == aList[i-1]:
aList[i] = aList[0]
return aList
shift(aList=[1,2,3])
With Python, we can easily shift the items in a list both to the right or the left. To shift items to the left, we can remove the first element from the list with pop(), and then append it to the end of the list with the append() function. To shift items to the right, we can do the opposite.
Method #2 : Using insert() + pop() This functionality can also be achieved using the inbuilt functions of python viz. insert() and pop() . The pop function returns the last element and that is inserted at front using the insert function.
Here is the solution for your query. a=["first","second from last","last"] # A sample list print(a[0]) #prints the first item in the list because the index of the list always starts from 0. print(a[-1]) #prints the last item in the list. print(a[-2]) #prints the last second item in the list.
To shift the bits of array elements of a 2D array to the left, use the numpy. left_shift() method in Python Numpy. Bits are shifted to the left by appending x2 0s at the right of x1.
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]
You can use this:
li=li[-1:]+li[:-1]
You can use negative indices together with list concatenation:
def shift(seq, n=0):
a = n % len(seq)
return seq[-a:] + seq[:-a]
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 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With