I'm working on a simple left circular shift function as an exercise (ie feed it [1,2,3]
and it returns [[1,2,3],[2,3,1],[3,1,2]]
). If I use this version of the code:
def left_shifts(L):
if len(L) == 0:
M = []
elif len(L) == 1:
M = deepcopy(L)
else:
M = [len(L)]
M[0] = L
for i in range(1,len(L)):
M[i] = (L[i:] + L[:i])
return M
print (left_shifts([1,2,3,4,5]))
I get an error that the list assignment index is out of range. However, if I just tweak it to this:
def left_shifts(L):
if len(L) == 0:
M = []
elif len(L) == 1:
M = deepcopy(L)
else:
M = [len(L)]
M[0] = L
for i in range(1,len(L)):
M.append((L[i:] + L[:i])) #changed line
return M
print (left_shifts([1,2,3,4,5]))
It works fine. My question is: why would the upper code generate this error? All I'm doing is adding two lists together and assigning it to one element of another list, which I would think would be legal.