Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does changing a value in a sublist changes all sublists

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading