In x = len(d) * [dict().copy()][:]
, the dict
function is run only once. Consequently, all three dictionaries are the same. If you want three different dictionaries, you need to run it three times, e.g.:
>>> x = [dict() for i in range(3)]
>>> x
[{}, {}, {}]
>>> x[0]['x'] = 'u'
>>> x
[{'x': 'u'}, {}, {}]
>>>
More
Python cannot multiply a list until after it has created the list. Thus, when 3 * [dict()]
is executed, dict
is evaluated first and then the multiplication is performed. The same is true of 3*[int(1)]
but notice a difference that may seem confusing at first:
>>> x = 3*[int(1)]
>>> x
[1, 1, 1]
>>> x[0] = 2
>>> x
[2, 1, 1]
Superficially, this might seem inconsistent with the case of the multiplied list of dictionaries. The difference here is that the assignment statement x[0] = 2
does not modify the properties of x[0]
; it replaces x[0]
with a new element. Consequently, the result is different.
The concept of replacement also applies to dictionaries. Consider:
>>> x = 3 * [dict()]
>>> x
[{}, {}, {}]
>>> x[0] = dict(x='u')
>>> x
[{'x': 'u'}, {}, {}]
Even thought the three dictionaries in x
start out as the same, the statement x[0] = dict(x='u')
replaces the first dictionary with a new one.