Python anomaly

Quite frankly, the following quirk of Python has driven me up the wall for the past half-hour:

>>> myListOfLists = [[0.0]*2]*3
>>> myListOfLists[0][1] = 1.0
>>> myListOfLists
[[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]]


>>> myListOfLists = [[0.0]*2, [0.0]*2, [0.0]*2]
>>> myListOfLists[0][1] = 1.0
>>> myListOfLists
[[0.0, 1.0], [0.0, 0.0], [0.0, 0.0]]

See the difference? Indices remain linked in the former instance where the outer list is initially populated by multiplication, whereas they do not in the latter where the outer list is constructed “manually”.

But when I populate the outer list by addition, instead of multiplication, the indices remain unlinked.

>>> myListOfLists = [[0.0]*2] + [[0.0]*2] + [[0.0]*2]
>>> myListOfLists[0][1] = 1.0
>>> myListOfLists
[[0.0, 1.0], [0.0, 0.0], [0.0, 0.0]]

Why, oh why?

Posted

Testing...

Submitting to temptation and seeing how this site works.

Posted