The question is to write a shift_right
function so that it shifts every element in the list to the right. For instance, if the list is
L = [\'a\',\
I just figured out the answer for the question. Its as follows.
def shift_right(L):
last_item = L[-1]
for i in range(1, len(L)):
L[len(L) - i] = L[len(L) - i - 1]
L[0] = last_item
I'd implement it like this:
def shift_right(L):
if len(L) > 0:
L.insert(0, L.pop())
As Lee correctly comments, this is a rotate operation rather then a shift.
I'll add this in for completeness.
If you are shifting several at at time you can use something like
def rotate(L, n):
if len(L) is not 0:
shift = n % len(L)
L[:shift], L[shift:] = L[-shift:], L[:-shift]
If you are doing this often throughout your program, it could be worthwhile to use a deque. You can convert your list to a deque like this:
from collections import deque
L = deque(L)
then to rotate it n spaces to the right, you can use
L.rotate(n)
If you want to convert it back into a list, you can do
L = list(L)
It is better to avoid converting back and forth, since it takes as much time as several rotations in the list. Deques work best when you are accessing, adding, and deleting around their beginnings and ends.