So I have a 4 by 3 nested list (4 rows, 3 columns) that I have nested as follows:
>>> c= [x[:] for x in [[None]*3]*4]
>>> print c
[[None, None, None],
[None, None, None],
[None, None, None],
[None, None, None]]
I have initialized my nested list in this fashion because this other SO question does a good job of explaining why some other methods don't work. (like c = [[None]*3]*4)
Now I want to update all elements in the first row to 0. i.e. I want to set all elements in
c[0] to 0. So I tried the following:
>>> for x in c[0]: x = 0
...
>>> c
[[None, None, None], [None, None, None], [None, None, None], [None, None, None]]
>>>
As you can see, the elements were not updated. The following worked however:
>>> c[0] = [0 for x in c[0]]
>>>
>>> c
[[0, 0, 0], [None, None, None], [None, None, None], [None, None, None]]
And I was almost sure it would because I'm creating a new list of 0s and assigning it to c[0].
Anyway, I then went on to use the for loop and tried to update the first column (i.e. the first element of every row) to 0 and that worked.
>>> for x in c: x[0] = 0
...
>>> c
[[0, None, None], [0, None, None], [0, None, None], [0, None, None]]
I understand that this for loop update is different from the previous for loop update since the first one tried to loop over single elements while this one loops over lists and just accesses the first element of each list.
I'm sure I'm missing something about names pointing to other names but I can't put my finger on what the exact issue is here. Could someone please help?