I am trying to set a specific value of a 2D array to True. Here is the snippet of code:
b [ [False] * 3] * 3
b[2][1] = True
Unfortunately, this is setting the entire row to True (so b[0][1]
would then be changed to True). Any ideas on what is going on?
EDIT:
Just tried this code and it worked:
b = []
for i in range(3):
b.append([False, False, False])
b[1][2] = True
Why would it work in that case and not the former?
[[False]*3]*3
creates three references to the same [False,False,False]
object, thus when you change one item, your other rows/cols change as well.
Your second version avoids this by createing a new [False, False, False]
object for every row/col.