Possible Duplicate:
Python list append behavior
Why does this code:
x = [[]]*3
x[0].append('a')
x[1].append('b')
x[2].append('c')
x[0]=['d']
print x
print [[‘d’], [‘a’, ‘b’, ‘c’], [‘a’, ‘b’, ‘c’]]?
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.
This is best explained step by step:
>>> x = [[]]*3 >>> x [[], [], []] >>> x[0].append('a') >>> x [['a'], ['a'], ['a']] >>> x[1].append('b') >>> x [['a', 'b'], ['a', 'b'], ['a', 'b']] >>> x[2].append('c') >>> x [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']] >>> x[0]=['d'] >>> x [['d'], ['a', 'b', 'c'], ['a', 'b', 'c']]The first statement creates a list with three references to the same element in it. So when you modify the first element, you’re also modifying the second and third element. Hence, the append statements add a number to each of the elements of the list.