How to copy a list which is consisted of list type elements? I have used the method described in a similar question how to clone a list? But it still doesn't work, as shown in picture below
Original code is
asd
a = [[]]
b = list(a)
for i in [1,2]:
for j in b:
j.append(i)
print a
why would a
change when b
was changed? But I want to keep a
from being changed.
Requirements: cannot import package such as copy
since I met this problem in leetcode.com.
Finally, the answer is that I need a deep copy of list, that is
b = [c[:] for c in a]
. Notice: as @PM2Ring mentioned below at comment area, b = [c[:] for c in a]
is only suited for a single level of nesting. For more complicated deep copy, look for phrase "deep copy". Thanks for all your help.