This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Wrong behavior for list of lists
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Bastiaan Albarda, dechamps, martin.panter, zorceta
Priority: normal Keywords:

Created on 2015-07-08 08:01 by dechamps, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (4)
msg246450 - (view) Author: Jos Dechamps (dechamps) Date: 2015-07-08 08:01
After creating a list of lists, changing one element, leads to changes of all the elements:

>>> v=[[]]*10
>>> v
[[], [], [], [], [], [], [], [], [], []]
>>> v[3].append(3)
>>> v
[[3], [3], [3], [3], [3], [3], [3], [3], [3], [3]]
>>> 
>>> v=[[]]*10
>>> v
[[], [], [], [], [], [], [], [], [], []]
>>> v[3] += [3]
>>> v
[[3], [3], [3], [3], [3], [3], [3], [3], [3], [3]]
>>>
msg246451 - (view) Author: Zorceta (zorceta) Date: 2015-07-08 08:51
FYI:

>>> ll = [[]]*10
>>> [id(l) for l in ll]
[67940296, 67940296, 67940296, 67940296, 67940296, 67940296, 67940296, 67940296, 67940296, 67940296]
msg246454 - (view) Author: Bastiaan Albarda (Bastiaan Albarda) Date: 2015-07-08 09:53
The * operator lets you use the same object multiple times, thereby saving resources. 

If you want unique objects use comprehension:
>>> v = [[] for x in range(10)]
>>> v[3].append(3)
>>> v
[[], [], [], [3], [], [], [], [], [], []]
>>> v[3] += [3]
>>> v
[[], [], [], [3, 3], [], [], [], [], [], []]
msg246455 - (view) Author: Martin Panter (martin.panter) * (Python committer) Date: 2015-07-08 11:07
This is how Python is meant to work; see <https://docs.python.org/2.7/faq/programming.html#how-do-i-create-a-multidimensional-list>. Unless there is something in the documentation that gave you the wrong impression, I suggest we close this.
History
Date User Action Args
2022-04-11 14:58:18adminsetgithub: 68777
2015-07-08 11:08:12martin.pantersetstatus: open -> closed
stage: resolved
2015-07-08 11:07:38martin.pantersetresolution: not a bug

messages: + msg246455
nosy: + martin.panter
2015-07-08 09:53:24Bastiaan Albardasetnosy: + Bastiaan Albarda
messages: + msg246454
2015-07-08 08:51:38zorcetasetnosy: + zorceta
messages: + msg246451
2015-07-08 08:01:16dechampscreate