1

The following function (taken from this SO question) works fine as long as number of rotations does not exceed the number of elements in list. After that it just repeats the original list. Is there any modification that can be done to rotate a list any number of times?

def shift(l,n):
  return l[n:] + l[:n]

sample output

Vishal
  • 35
  • 1
  • 1
  • 5

2 Answers2

3

Apply modulo to the argument:

def shift(l,n):
  if not len(l): # to avoid error on modulo operator
    return [] 
  n = n % len(l)
  return l[n:] + l[:n]
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Suppose you have five elements in the list, and the rotation number is eight, then you basically need to rotate your list just for three times. Because at the fifth rotation, your list is same as original list, so remaining three times you need to rotate.

def left_shift(lst, n):
 n= n % len(lst)
 return lst[n:]+lst[:n]
 
def right_shift(lst, n):
  n= n % len(lst)
  return lst[-n:] + lst[:-n]
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77