Python Forum

Full Version: Multiple items of a matrix has been updated.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey everyone, I an new in Python and I want to update an item of a matrix, but 3 items are updated. I am not sure why this happens.
Please check the following code:

	Board = []
	rows = ["_" for i in range(3)]
	for index in range(3):
		Board.append(rows)

	Board[0][0] = "1"
	print(Board)
The current Output is:
[['1', '_', '_'], ['1', '_', '_'], ['1', '_', '_']]
The expected Output should be:
[['1', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
Only one row was updated. The problem is that your matrix only has one rows.
(May-19-2020, 12:25 PM)deanhystad Wrote: [ -> ]Only one row was updated. The problem is that your matrix only has one rows.

Hey thanks for the hint! I have updated the creation of the Board as the following:
Board = [ ["_" for i in range(3)] for j in range(3) ]
However, I still don't know why my original code will create 1 row matrix:
Board = []
rows = ["_" for i in range(3)]
for index in range(3):
    Board.append(rows)
If we do print(Board) both code will generate the same output:
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
Which is a list of 3 lists
What would you expect to see as output?
a = [1, 3, 3]
b = a
b.append(4)
print(a)
If still confused, try adding this line and run again
print(id(a), id(b))
b is not a copy of a, it is a. a and b are the same list. When you build your Board you are using the same rows for each row in the Bostf. If you did print(id(Board[0]), id(Board[1])) you would see they are the same and not two different lists.
Thanks for the clear explanation!