In the latest Python (3.2):
>>> l = [{}]*2
>>> l[1]['key'] = 'value'
>>> l
[{'key': 'value'}, {'key': 'value'}]
I expected l to be [{}, {'key': 'value'}] after this operation. Is it normal behaviour or a bug?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Normal. Try using
l = [{} for x in range(2)]instead.[{}]*2does 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.