Home > Blockchain >  Why does a list change when i change another?
Why does a list change when i change another?

Time:10-12

the "startboard" list changes when im not doing it

 def moves(board, player):
  boardlist=[]
  for x in range(7):
    newboard=board
    if board[5][x]==0:
      place=0
      if player:
        newboard[place][x]=1
      else:
        newboard[place][x]=2
      boardlist.append(newboard)
  return boardlist

startboard=[[0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0]]

moves(startboard, True)

i added indexes at newboard=board[:][:] and it still didnt work

how can i stop the startboard list from changing?

CodePudding user response:

try:

from copy import deepcopy
 def moves(board, player):
  boardlist=[]
  for x in range(7):
    newboard = deepcopy(board)
    if board[5][x]==0:
      place=0
      if player:
        newboard[place][x]=1
      else:
        newboard[place][x]=2
      boardlist.append(newboard)
  return boardlist

startboard=[[0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0]]

moves(startboard, True)

You can find explanation here: https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/

CodePudding user response:

newboard=board[:][:] is a shallow copy, it has the same references as the original object. The docs explain the difference between shallow and deep copies:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Here's a little demonstration:

import copy

a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]

Using normal assignment operatings to copy:

d = c

print id(c) == id(d)          # True - d is the same object as c
print id(c[0]) == id(d[0])    # True - d[0] is the same object as c[0]

Using a shallow copy:

d = copy.copy(c)

print id(c) == id(d)          # False - d is now a new object
print id(c[0]) == id(d[0])    # True - d[0] is the same object as c[0]

Using a deep copy:

d = copy.deepcopy(c)

print id(c) == id(d)          # False - d is now a new object
print id(c[0]) == id(d[0])    # False - d[0] is now a new object
  • Related