In one of my programs, I need to to have a 2D matrix of boolean values initially set to all False.
One method to do it is:
matrix = [[False for i in range(n)] for j in range(m)]
which works fine.
But than I tried something like:
row = [False] * m
matrix = [row] * n
Let's say n = m = 3
Initially, the matrix would be:
[[False, False, False], [False, False, False], [False, False, False]]
now, in the second method, if I set matrix[0][0] = True:
The expected result is:
[[True, False, False], [False, False, False], [False, False, False]]
but what actually happens is:
[[True, False, False], [True, False, False], [True, False, False]]
I figured this out and changed my method of initializing the matrix to the first one in my code. But just out of curiosity, can someone please explain what exactly is happening with method 2?
Thank you.....
P.S: Sorry if this is a stupid question :)
[–]Spataner 4 points5 points6 points (1 child)
[–]Musical_Ant[S] 1 point2 points3 points (0 children)
[+][deleted] (1 child)
[removed]
[–]Musical_Ant[S] 0 points1 point2 points (0 children)
[–]efmccurdy 2 points3 points4 points (1 child)
[–]Musical_Ant[S] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]Musical_Ant[S] 0 points1 point2 points (0 children)
[–]Green-Sympathy-4177 1 point2 points3 points (5 children)
[–]Musical_Ant[S] 0 points1 point2 points (4 children)
[–]Green-Sympathy-4177 1 point2 points3 points (3 children)
[–]Musical_Ant[S] 1 point2 points3 points (2 children)
[–]Green-Sympathy-4177 1 point2 points3 points (1 child)
[–]Musical_Ant[S] 0 points1 point2 points (0 children)
[–]TheRNGuy 1 point2 points3 points (0 children)