How can this be explained?
x = [[]]*3 x[0].append('a') print(x)>>> returns [['a'], ['a'], ['a']]
Why does this list of lists end up with the same values
|
How can this be explained?
x = [[]]*3 x[0].append('a') print(x)>>> returns [['a'], ['a'], ['a']]
Jul-18-2019, 11:48 AM
After you execute
x = [[]]*3 , x is a list containing 3 references to the same list. Basically, you've given the inner list three names: x[0] , x[1] and x[2] .When you modify the list, you can see the change no matter which name you use. The same would happen if you did this: >>> a = b = [] >>> a.append(1) >>> b [1]You probably wanted to create 3 distinct lists, e.g.: x = [[] for _ in range(3)]
Jul-18-2019, 12:34 PM
You can read or watch Ned Batchelder's Python Names and Values. This should answer you question in pretty comprehensive way.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame. |
|