Issue 25681: Assignment of one element in nested list changes multiple elements (original) (raw)
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)
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'], ['', ''], ['', '']]
Author: Anilyka Barry (abarry) *
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.
Author: Anilyka Barry (abarry) *
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.
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:24
admin
set
github: 69867
2015-11-20 15:00:56
vstinner
set
status: open -> closed
resolution: not a bug
2015-11-20 14:53:59
ydu
set
messages: +
2015-11-20 14:48:06
abarry
set
messages: +
2015-11-20 14:43:03
abarry
set
nosy: + abarry
messages: +
2015-11-20 14:39:48
ydu
create