Home > other >  Is there a way to deepcopy a list without importing copy.deepcopy?
Is there a way to deepcopy a list without importing copy.deepcopy?

Time:10-16

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])
  • Related