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: Assignment of one element in nested list changes multiple elements
Type: behavior Stage:
Components: Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: abarry, ydu
Priority: normal Keywords:

Created on 2015-11-20 14:39 by ydu, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (4)
msg254978 - (view) Author: Yan (ydu) Date: 2015-11-20 14:39
Is this the correct behavior?

>>> l=[['']*2]*3
>>> b=[['', ''], ['', ''], ['', '']]
>>> l == b
True
>>> l[0][1]='A'
>>> b[0][1]='A'
>>> l == b
False
>>> l
[['', 'A'], ['', 'A'], ['', 'A']]
>>> b
[['', 'A'], ['', ''], ['', '']]
msg254980 - (view) Author: Anilyka Barry (abarry) * (Python triager) Date: 2015-11-20 14:43
Your list `l` actually holds only one list, except three times. When you change it, it's reflected in all the lists. It's the equivalent of the following:

>>> x=['', '']
>>> l=[x, x, x]

Makes a bit more sense this way? Either way, yes, this is intentional behaviour.
msg254982 - (view) Author: Anilyka Barry (abarry) * (Python triager) Date: 2015-11-20 14:48
Another way to fix this would be the following:

>>> l=[[''] * 2 for _ in range(3)]
>>> l
[['', ''], ['', ''], ['', '']]
>>> l[0][1] = "A"
>>> l
[['', 'A'], ['', ''], ['', '']]

The * operator on lists doesn't create new elements, it only adds new references to them. A list comprehension will evaluate the expression each time, while repetition (the * operator) will only evaluate it once.
msg254983 - (view) Author: Yan (ydu) Date: 2015-11-20 14:53
Thanks for the quick response.
It makes sense to me. I misunderstood the * operator.
History
Date User Action Args
2022-04-11 14:58:24adminsetgithub: 69867
2015-11-20 15:00:56vstinnersetstatus: open -> closed
resolution: not a bug
2015-11-20 14:53:59ydusetmessages: + msg254983
2015-11-20 14:48:06abarrysetmessages: + msg254982
2015-11-20 14:43:03abarrysetnosy: + abarry
messages: + msg254980
2015-11-20 14:39:48yducreate