-1

So in my free Time I've been trying to make a little Programm, however I've run into a slight problem. I want to change some things in a copied list, but for some reason the changes get caried over to the original/base list.

from random import *

a = [[0,5,9,5,9,4,0,0,5],
[0,0,7,0,0,3,0,0,3],
[0,0,5,0,0,0,7,8,45]]
b = a.copy()

for x in range(len(b)):
 for y in range(len(b[1])):
  if b[x][y] == 0:
   b[x][y] = randint(10, 100000)
  

if a == b:
 print("Not working")

print(b)
print(a)

I have also tried b = list(a) and with the copy library, but all my changes to b still get carried over to a, resulting in a == b being true. Does someone know what the problem is or what I'm doing wrong/misunderstanding? Help would be very appreciated and thanks in advance.

  • 3
    You're only copying the top-level list, which contains references to lists which are copied as references. What you want is a deep copy, available through `import copy; b = copy.deepcopy(a)`. – L3viathan Jul 06 '20 at 14:19
  • You can read about shallow copy and deepcopy https://realpython.com/copying-python-objects/ – Arpit Svt Jul 06 '20 at 14:23

2 Answers2

0

You have a list of lists, thus you need to deepcopy a to avoid mutating a:

import copy

a = [[0,5,9,5,9,4,0,0,5],
[0,0,7,0,0,3,0,0,3],
[0,0,5,0,0,0,7,8,45]]
b = copy.deepcopy(a)

Short explanation: You copy the outer "structure" of list a, while the "inner structure" is still consisting of references to the "sub"-level lists. Thus the second level of b still refers to the same elements in a. copy.deepcopy avoids this problem by copying all mutable elements of an object down to a certain depth.

JE_Muc
  • 5,403
  • 2
  • 26
  • 41
  • Thank you very much for the swift answer, I had forgotten that the lists would count as object and that caused this problem. – Nichtsoeren Jul 06 '20 at 14:37
  • You are welcome and my still upvote and accept my answer, since it was the first to answer your question. :) – JE_Muc Jul 06 '20 at 15:16
0

You must use deepcopy to copy everything, otherwise you copy only the top level list.

For example:

from random import *
from copy import deepcopy

a = [[0,5,9,5,9,4,0,0,5],
[0,0,7,0,0,3,0,0,3],
[0,0,5,0,0,0,7,8,45]]
#use this
b=deepcopy(a)
#instead of this
#b = a.copy()

for x in range(len(b)):
 for y in range(len(b[1])):
  if b[x][y] == 0:
   b[x][y] = randint(10, 100000)
  

if a == b:
 print("Not working")

print(b)
print(a)

You can read about the difference between shallow and deep copy in the official documentation.

Mayhem
  • 487
  • 2
  • 5
  • 13