I stumbled upon an intriguing behaviour of a list of string lists in Python 3.7.3. I define the lists of lists as below, and update an element:
s = [['']*2]*2
s[1][1] = 'why?'
print(s)
It prints:
[['', ''], ['', '']]
[['', 'why?'], ['', 'why?']]
I cannot figure out why is not updated the right element.
A first thought was to define s = [[' ']*2]*2
, with 4 spaces = len('why?')
, as elements, but the wrong update persists.
Redefining the list s
explicitly, and performing the same update as above, I get the right result:
s = [['', ''], ['', '']]
s[1][1]= 'why?'
print(s)
[['', ''], ['', 'why?']]
I'm working with such lists as lists of tooltips associated to large heatmaps. I can avoid this issue converting the list of n-spaces lists to a np.array
, but I'd like to know why the above odd update occurs. Thanks!