Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to build a gameboard that is a 5x5 grid in python 2.7 represented as a 2 dimensional list. I tried writing it as board = [["O"]*cols]*rows (cols and rows are already declared to be 5) but when I try to edit the value at an index it changes the entire row. For example

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 value of an index like:

board[1][1] = "X"

it 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 only the value at row 1 col 1 to change.

I also tried doing the following:

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

This one works like I want it to. What I want to understand is what is the difference?

like image 538
marisbest2 Avatar asked Oct 26 '25 02:10

marisbest2


1 Answers

if you evaluate the expression below you will see it will return True for your first example, but False for the other. Both lists are actually pointing to the same single list in memory.

board[0] is board[1]

if you do want to have a short version that makes distinct new lists, then this version will work correctly too.

board = [["O"]*cols for y in range(rows)]
like image 108
Marwan Alsabbagh Avatar answered Oct 29 '25 09:10

Marwan Alsabbagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!