x = [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
b = x[:]
b[1].append(99)
print(x[1])
x[1]=[1, 2, 3, 99]
Using the builtin .copy() method b=x.copy()
is the same, x[1]=[1, 2, 3, 99]
and b = list(x)
is the same too, x[1]=[1, 2, 3, 99]
b=[i for i in x]
is the same too, x[1]=[1, 2, 3, 99]
only import copy
and b=copy.deepcopy(x)
is
x[1]=[1, 2, 3]
is there a way to make x[1]=[1, 2, 3]
without importing deepcopy() ?
CodePudding user response:
You have to copy the lists inside too:
x = [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
b = [v.copy() for v in x]
b[1].append(99)
print(x[1])
print(b[1])