Let's say I have the following empty two dimensional array in Python:
q = [[None]*5]*4
I want to assign a value of 5
to the first row in the first column of q
. Instinctively, I do the following:
q[0][0] = 5
However, this produces:
[[5, None, None, None, None],
[5, None, None, None, None],
[5, None, None, None, None],
[5, None, None, None, None]]
The first element of every array is being initialized to 5
, where I thought only the first element of the first array would get the update. I have two questions:
- Why is Python initializing the first value of every array and not just the first one?
- Is there a better way to accomplish what I'm trying to do?