0

I am fiddling with lists and I cannot understand why a copy of the list is modifing the original list.

winC is a set of parameters that will modify a given list.

originList is untouched.

Then newList is copy of originList, so that I can modify it and compare the results with the previous one.

winC = [[[1, 1, 1], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [1, 1, 1], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [1, 1, 1]],
        [[1, 0, 0], [1, 0, 0], [1, 0, 0]],
        [[0, 1, 0], [0, 1, 0], [0, 1, 0]],
        [[0, 0, 1], [0, 0, 1], [0, 0, 1]],
        [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
        [[0, 0, 1], [0, 1, 0], [1, 0, 0]]]


originList = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
newList = originList.copy()

print(originList)
print(newList)

for x in range(len(winC)):
    for y in range(len(winC[x])):
        for z in range(len(winC[x][y])):
            if winC[x][y][z] == 1:
                newList[y][z] += 1     ## Note that newList is being modified, not originList

print(originList)
print(newList)

When I run this code, originList and newList are changed, despite the fact that I only modified newList. I've tried using .copy(), list(originList) and originList[:], and none of those seem to work. I am still using Python 3.9.6 What should I do?

SantiClaw
  • 7
  • 2

1 Answers1

0

The reason it doesn’t work is that it’s copy just produces a shallow copy. You are just creating a new variable that points to the same data in memory. Try this instead of your copy line.

import copy

newList = copy.deepcopy(originalList)
anarchy
  • 3,709
  • 2
  • 16
  • 48