Python Forum

Full Version: Why does this list of lists end up with the same values
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can this be explained?
x = [[]]*3
x[0].append('a')
print(x)
>>> returns [['a'], ['a'], ['a']]
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)]
You can read or watch Ned Batchelder's Python Names and Values. This should answer you question in pretty comprehensive way.