Home > database >  Why clearing a list of a list clears all lists
Why clearing a list of a list clears all lists

Time:03-24

In this code I'm adding zeros to an empty list, then when it contains 9 zeros that list is added to another list which is called board, then I clear the row of 9 zeros and repeat the process 9 times again:

    row = []
    for i in range(9):
        for j in range(9):
            row.append('0')
        self.board.append(row)
        row.clear()
    print(board)

After some prints I've understand that before the outer loop ends the board contains all 9 rows of 9 zeros but when row.clear() is executed for the last time it clears all the rows of zeros giving me a result of a list that contains 9 empty lists, which of course is not what I want, I know how to solve it but I don't understand why when the loop reaches the end all internal lists of zeros are clear.

CodePudding user response:

You have a single row list instance that exists 9 times in self.board. Clearing one has the effect of clearing them all, since they're all the same list.

At the simplest, you'll need to (shallow-)copy the list, so there are 9 separate lists:

self.board.append(row[:])
# or
self.board.append(list(row))

(Shallow-copying here is fine, since the value within is a string, and strings are immutable.)

You could also use a list comprehension and the fact you can multiply a list to repeat it to populate your board in one swoop:

self.board = [['0'] * 9 for x in range(9)]

CodePudding user response:

based on this

If the objects are mutable, append will only add the pointer to that board object (not the value)

you can use .copy() to copy the value

self.board.append(row.copy())

if you dont want to update it

  • Related