-3

I noticed this problem in something I was making, and managed to reproduce it in a simpler form.

The problem is that I have two players - both of a Person class - and they each have their own grid. I start off with a global grid variable and assign each Person's grid to that global variable. However, when I change one Person's grid, the other Person's grid changes, too!

Here's the code and output:

Code image

Anyone have any suggestions as to why this happens?

EDIT:

I tried the list() suggestion. This worked in one program, but in my main program it didn't do anything.

Players[1].Grid = list(Grid)

Players[0].Grid = list(Grid)

This outputs the same thing when I changed on of the lists.

Woafer
  • 11
  • 1
  • 4

2 Answers2

0

You're sharing the grid between both objects, so when you change it, they both see it. If you want each to have a copy of it, use list() to make a copy of it.

People[a].grid = list(Grid)
Scovetta
  • 3,112
  • 1
  • 14
  • 13
0

Although Scovetta's answer did work for the example I provided, the code in which I found the problem actually used a 2-Dimensional list, rather than the 1-Dimensional one in the sample.

I have found out from here that more complex objects need

copy.deepcopy

to copy everything, without being just a reference to the old variable.

Community
  • 1
  • 1
Woafer
  • 11
  • 1
  • 4