0

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!

xecafe
  • 740
  • 6
  • 12
  • 1
    See this: [multi-dimensional lists](https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list) – Sayandip Dutta Dec 27 '19 at 10:27
  • *replicating a list with * doesn’t create copies, it only creates references to the existing objects* – azro Dec 27 '19 at 10:28
  • Also see [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/q/240178/5431791) – Sayandip Dutta Dec 27 '19 at 10:29
  • 1
    Does this answer your question? [python \* operator, creating list with default value](https://stackoverflow.com/questions/29306418/python-operator-creating-list-with-default-value) – luis.parravicini Dec 27 '19 at 10:30
  • Thank you @SayandipDutta ! It's for the first time when I encountered this issue. I didn't know about the details pointed out in your link to docs. – xecafe Dec 27 '19 at 11:06
  • @xecafe No problem, it happens. Actually, in most of the cases when you come up with a question, chances are the question has already been asked and answered on SO, so I would suggest you to research thoroughly before asking. Try searching with different keywords. Anyway, glad to help! – Sayandip Dutta Dec 27 '19 at 11:10

0 Answers0