0

I have a list which is full of None. How to replace only one element without affecting the others. I understand that this is due to python shallow copying:

>>> a = [[None] * 3] * 3
>>> a
[[None, None, None], [None, None, None], [None, None, None]]
>>> a[0][1] = 2
>>> a
[[None, 2, None], [None, 2, None], [None, 2, None]]

I would like:

>>>a[0][1] = 2
[[None, 2, None], [None, None, None], [None, None, None]]

I know this can be done using a list comprehension like:

>>> a = [[None] * 3 for _ in range(3)]
>>> a
[[None, None, None], [None, None, None], [None, None, None]]
>>> a[0][1] = 2
>>> a
[[None, 2, None], [None, None, None], [None, None, None]]

But I was wondering if there was another way around? Something more pythonic?

I need this because bokeh's grid does not seem to accept anything else than a None in order not to have a graph. If you know a better alternative. (In this case a[0][1] would be replaced by a plot).

tupui
  • 5,738
  • 3
  • 31
  • 52
  • The three lists are the same list. – Peter Wood Jul 25 '17 at 07:43
  • @PeterWood Yeah I know but then how to accomplish what I seek?? I can do it using a list comprehension I guess but is there a better alternative? – tupui Jul 25 '17 at 07:45
  • 2
    They all have same `id`, because you are creating duplicate `None`, Refer this too https://stackoverflow.com/questions/1959744/python-list-problem – Bijoy Jul 25 '17 at 07:46
  • 1
    @Bijoy thanks for the link the answer has a good link to it! – tupui Jul 25 '17 at 07:48
  • @Y0da put that in your question. You haven't said you understand that you need to change how the list of lists is created. If you know how to do it with a list comprehension, put that in the question too. – Peter Wood Jul 25 '17 at 07:58

0 Answers0