Hi, I am new to python need help with making list copies!
def rotate(lst):
a=lst[:]
#a=lst[:] / =lst.copy() / =[x for x in lst] e.t.c does not work but a=[[0,0,0],[0,0,0],[0,0,0]] works # # # how?
for i in range(len(lst)):
for j in range(len(lst)):
a[j][i]=lst[len(lst)-i-1][j]
return a
lst=[[1,2,3],[4,5,6],[7,8,9]]
print(rotate(lst))
print(lst)
Expected answer (obtained when a=[[0,0,0],[0,0,0],[0,0,0]]):
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Answer obtained when using a=lst[:] | a =lst.copy() | a =[x for x in lst]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[7, 8, 7], [8, 5, 8], [9, 6, 7]]
[[7, 8, 7], [8, 5, 8], [9, 6, 7]]
a=[[0]*len(lst)]*len(lst) gives a wrong answer too even though it essentially means a=[[0,0,0],[0,0,0],[0,0,0]])
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[9, 6, 3], [9, 6, 3], [9, 6, 3]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Why does this happen? why does the deep copy not work in this case?