Home > database >  Why does changing a value in a sublist changes all sublists
Why does changing a value in a sublist changes all sublists

Time:07-19

I'm trying to make lists within a list that has a special character to represent a player's position, in this case '@':

def __init__(self, x, y, plrX, plrY): # simplified for question
        self.board = []
        boardX = []
        self.x = x # x and y set to 10
        self.y = y
        self.plrX = plrX # set to 3
        self.plrY = plrY # set to 7
        a = 0
        b = 0
        
        while b < self.x: # Makes a list that looks similar to this ['-','-','-']
             boardX.append('-')
             b  = 1
     
        while a < self.y: # Adds above list to make somthing like this: ['-','-','-']
            self.board.append(boardX) #                                 ['-','-','-']
            a  = 1

        self.board[self.plrY][self.plrX] = '@'

After the board is made, it's put through a method that prints it out nicely

for x in self.board:
    x = str(x).replace(',',"")
    x = x.replace("'","")
    print(x.strip("[]"))

What it prints out is this:

--@-------
--@-------
--@-------
--@-------
--@-------
--@-------
--@-------
--@-------
--@-------
--@-------

But what I was wanting was to print out '@' at the seventh sublist on the third character, like this:

----------
----------
----------
----------
----------
----------
--@-------
----------
----------
----------

What is causing the repeated @ character and how do I get the results I'm trying to get?

CodePudding user response:

Lists in Python do not copy, they alias. This means that if you have a list A, and do B = A, any change you make to A is also made to B (we can say that B references A). Instead of appending the same boardX multiple times, make a copy of it each time and add that copy. That way, each row is a distinct list, and not just a reference. You can simply do boardX.copy() and you will have a copy that can be used without affecting the original boardX

  • Related