0

I'm currently confused as to why one of my arrays is changing when it hasn't been called.

if 2 <= self.counter <= 3:
         print(self.old[y][x])
         self.grid[y][x] = 1
         print(self.old[y][x])

The first print displays 0 and the second print displays 1. I'm only changing the new version of the grid so I'm confused to why this value is changing. Earlier in the code (as seen below) I wrote self.old = self.grid so I can change the values in self.grid while still keeping the original grid.

Here is the full code:

# Rules
# Any live cell with 2/3 live cell survives
# Any dead cell with =3 live cells becomes a live cell
# All other cells die in the next generation.
# 0 - dead, 1 - alive

import os
from time import sleep


class Life:
  def __init__(self):
    self.grid = [[0, 0, 0, 0],
                [0, 1, 0, 0],
                [1, 1, 0, 0],
                [0, 0, 0, 0]]
    self.h = 3
    self.w = 3

  def check(self, y, x):
    if (0 <= x <= self.w) and (0 <= y <= self.h):
      if self.old[y][x] == 1:
        print("Pass", x,y)
        self.counter += 1

  def display(self):
    for item in self.grid:
      print(item)

  def display_old(self):
    for item in self.old:
      print(item)



  def start(self):
    for gen in range(0, 3):
      os.system("cls")
      print("Generation: ", gen)
      self.display()
      self.old = self.grid
      for y in range(0, 4):
        for x in range(0, 4):
          #print(y, x)
          print("\n")
          self.display_old()
          self.counter = 0

          # Checking neighbours

          self.check(y - 1, x - 1)  # Up/Left
          self.check(y - 1, x)  # Up
          self.check(y - 1, x + 1)  # Up/Right

          self.check(y, x - 1)  # Left
          self.check(y, x + 1)  # Right

          self.check(y + 1, x - 1)  # Down/Left
          self.check(y+1, x) # Down
          self.check(y+1, x+1) # Down/Right

          print(f"Neighbours around grid[{y}][{x}]:", self.counter)
          # Rules
          if 2 <= self.counter <= 3:
            print(self.old[y][x])
            self.grid[y][x] = 1
            print(self.old[y][x])
          else:
            self.grid[y][x] = 0

          self.display()
      sleep(1)


l = Life()
l.start()
Euan Hall
  • 1
  • 3
  • 1
    Python assignment stores a reference, doesn't copy the object – Mad Physicist Apr 16 '20 at 21:53
  • I changed `self.old = self.grid` to `self.old = list(self.grid)`, yet it still changed when the other array changed. I tested those two lists on a seperate file and it worked fine, so I'm not sure why it's not working. – Euan Hall Apr 17 '20 at 08:00
  • Turns out that it's still pointing to the original list when it's a 2D array as it only copies the outside list. I used deepcopy from copy. – Euan Hall Apr 17 '20 at 08:11

0 Answers0