0

I am trying to change one cell in one nested list, and get the cell changed in all the nested lists.

example:

>>> temp_list = [['a']*2]*3
>>> temp_list
[['a', 'a'], ['a', 'a'], ['a', 'a']]
>>> temp_list[2][0] = 'b'
>>> temp_list
[['b', 'a'], ['b', 'a'], ['b', 'a']]
>>> 
Cœur
  • 37,241
  • 25
  • 195
  • 267
tal rosler
  • 23
  • 1
  • This is because ['a']*2] make list of [address of 'a', address 'a'] rather than [data 'a', data 'a']. When you did assignment, then value of that address got updated instead of data. – Tarun Behal Nov 26 '15 at 09:12
  • It is not a bug. List is a mutable sequence type. Check this url: https://docs.python.org/2/library/functions.html#list – Adem Öztaş Nov 26 '15 at 09:18
  • Another interesting link to understand what is going on: https://en.wikibooks.org/wiki/Python_Programming/Lists#List_creation_shortcuts – Antwane Nov 26 '15 at 09:19

2 Answers2

2

I know, it sounds wrong, but ...

This is not a bug, it's a feature.

>>> [id(x) for x in temp_list]
[4473545216, 4473545216, 4473545216]

As you can see, they all share the same reference. Therefore, you need to create a copy of the list.

Markon
  • 4,480
  • 1
  • 27
  • 39
0

In 2.7 I get the same behavior. Each instance that results from the * expansion refers to the same variable.

>>> temp_list = [['a']*2]*3
>>> temp_list
[['a', 'a'], ['a', 'a'], ['a', 'a']]
>>> temp_list[2][0] = 'b'
>>> temp_list
[['b', 'a'], ['b', 'a'], ['b', 'a']]
>>> temp_list[1][0] = 'c'
>>> temp_list
[['c', 'a'], ['c', 'a'], ['c', 'a']]
>>> temp_list[1][1] = 'x'
>>> temp_list
[['c', 'x'], ['c', 'x'], ['c', 'x']]

See: Python initializing a list of lists

Community
  • 1
  • 1
obscurite
  • 349
  • 1
  • 6