The following code will solve your issue:
def moveHead():
global snakeList
snakeList.insert(0, snakeList[0].copy())
del snakeList[-1]
snakeList[0][1] += 30
What's supposed to happen is that is that the item shifted to the right except of the element in index 0. In the example mentioned, [0,0]
would turn into [25,25]
, and the line below the for loop would change the whole thing to [[25,55],[25,25]]
.
No. Note the indices are reversed by:
lenlist = list(range(1,len(snakeList)))
lenlist.reverse()
If len(snakeList)
is 4, then after this 2 lines the content of lenlist
is [3, 2, 1]
.
So the for loop operates in reverse order. If the content of snakeList
is [[0,0],[25,0],[50,0],[75,0]]
, then after processing the loop
for i in lenlist:
snakeList[i] = snakeList[i-1]
the content of the list is [[0, 0], [25, 0], [50, 0], [75, 0]]
What now happens is, that the 1st and 2nd element of the list refer to the same object.
So after the line
snakeList[0][1] += 30
The content of the list is [[0, 30], [0, 30], [25, 0], [50, 0]]
.
If you repeat the process, then the content of the list will change to [[0, 60], [0, 60], [0, 60], [25, 0]]
and further [[0, 90], [0, 90], [0, 90], [0, 90]]
. Now all the elements of the list refer to the same list object.
You can get rid of that, by doing a shallow copy (list.copy()
) of the list element (each element of the list is a list, too):
snakeList[i] = snakeList[i-1].copy()
If you want to move the elements of the list to the right, then appending a new element at the head of the list and deleting the tail element of the list will do the job, too:
snakeList.insert(0, snakeList[0].copy())
del snakeList[-1]