Is it normal behaviour for python?
In the latest Python (3.2):
>>> l = [{}]*2
>>> l[1]['key'] = 'value'
>>> l
[{'key': 'value'}, {'key': 'value'}]
I expected l to be [{}, {'key': 'value开发者_C百科'}]
after this operation. Is it normal behaviour or a bug?
Normal. Try using l = [{} for x in range(2)]
instead.
[{}]*2
does not actually make 2 different dictionaries - it makes a list with two references to the same dictionary. Thus, updating that dictionary makes changes show up for both items in the list, because both items are actually the same dictionary, just referenced twice.
[{}]*2
doesn't result in a list with two dictionaries, it results in a list with the same dictionary twice. Use [{} for x in range(2)]
instead.
This code produces the same result over on Codepad for v 2.5.1
import sys
print sys.version_info
l = [{}]*2
l[1]['key'] = 'value'
print l
精彩评论