In Python 2.7, why grid = [["A"] * 5] * 5 is different from grid = [] grid.append [...]

I am trying to build a game board, which is a 5x5 grid in python 2.7, presented as a 2-dimensional list. I tried to write it as board = [["O"]*cols]*rows (cols and rows are already declared as 5), but when I try to change the value in the index, it changes the whole row. for instance

 cols = 5 rows = 5 board = [["O"]*cols]*rows 

this prints:

 [['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']] 

now when i try to change the index value like:

 board[1][1] = "X" 

he prints:

 [['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O']] 

I want to change only the value in line 1 col 1.

I also tried to do the following:

 board = [] for i in xrange(5): board.append(["O"]*cols) 

This one works the way I want. What I want to understand, what is the difference?

+4
source share
3 answers

if you evaluate the expression below, you will see that it will return True for your first example, but False for another. Both lists actually point to the same list in memory.

board[0] is board[1]

if you want to have a short version that makes different new lists, then this version will also work correctly.

 board = [["O"]*cols for y in range(rows)] 
+5
source

Because Python has no habit of implicitly copying things. [x] * 5 means "a list of 5 things, each of which x ". If you change one, you change them all, because they are all x - not copies of x .

When you use .append() , you force the copy, because every time through the loop you create a value added from scratch.

Yes, ["O"] * 5 creates a list of 5 things, each of which is the same "O" . However, this is not relevant; it doesn't make sense "another "O" " because you cannot change the "O" - no matter what you do with the variable that calls "O" , the "O" is still "O" .

+1
source

Your first expression creates a list of pointers to a single list object. Therefore, when updating one item, it changes everywhere.

0
source

Source: https://habr.com/ru/post/1437583/


All Articles