Python oddity #12

In [31]: [[],[]] == [[],] * 2
Out[31]: True

In [32]: a,b=[[],[]], [[],] * 2

In [35]: a[0]+=[1]

In [36]: a
Out[36]: [[1], []]

In [37]: b[0]+=[1]

In [38]: b
Out[38]: [[1], [1]]
Basically python tells that x + x = 2 * x but since [[],] * 2, does not do a deepcopy but a shallow one, modifying b[0] also modifies b[1]. I get caught by this infuriating inconsistency once every 4 years and I always swear it won't catch me again... until next time. The why and how at cpython level is detailed here

No comments: