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

Question:

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() ?

Asked By: bbiot426

||

Answers:

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])
Answered By: islam abdelmoumen
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.