Home > front end >  Copy/deep copy bug python
Copy/deep copy bug python

Time:09-12

Why does my list always copy like "mirroring" another variable though I already use "copy.deepcopy(var)" instead of "using var.copy()"?

Python Code:

import copy

after = [[[2,1]]]
for j in range(3):
    before = copy.deepcopy(after)
    after.clear()
    cond = "false"
    for i in range(len(before)):
        after.append(before[i])
        a_len = len(after)-1
        after[a_len].append([1,5])
        print(before)
        print(after)
        print("____")

Expected output:

[[[2, 1]]]
[[[2, 1], [1, 5]]]
____
[[[2, 1], [1, 5]]]
[[[2, 1], [1, 5], [1, 5]]]
____
[[[2, 1], [1, 5], [1, 5]]]
[[[2, 1], [1, 5], [1, 5], [1, 5]]]

Terminal output (now):

[[[2, 1], [1, 5]]]
[[[2, 1], [1, 5]]]
___
[[[2, 1], [1, 5], [1, 5]]]
[[[2, 1], [1, 5], [1, 5]]]
___
[[[2, 1], [1, 5], [1, 5], [1, 5]]]
[[[2, 1], [1, 5], [1, 5], [1, 5]]]

CodePudding user response:

You are appending a reference to the one of the original arrays elements here:

after.append(before[i])

So even after your deepcopy, you have an object from the original list in the copied list.

You need to deepcopy that as well. Or get a reference to the copy after you make the first deepcopy & use that here:

after.append(copy.deepcopy(before[i]))

Results:

[[[2, 1]]]
[[[2, 1], [1, 5]]]
____
[[[2, 1], [1, 5]]]
[[[2, 1], [1, 5], [1, 5]]]
____
[[[2, 1], [1, 5], [1, 5]]]
[[[2, 1], [1, 5], [1, 5], [1, 5]]]
____

  • Related