What is the difference between these two declarations of a list of lists?
>>> l = [[]]*4
>>> l
[[], [], [], []]
>>> l[1].append(1)
>>> l
[[1], [1], [1], [1]]
>>> m = [[],[],[],[]]
>>> m[1].append(1)
>>> m
[[], [1], [], []]
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.
The first one creates four references to a single list — it is the same list repeated four times. The second creates four distinct lists. In the first case, when you append to one list, it affects all of them, because they are all the same object. In the second case, each list is a distinct object, so appending to one doesn’t affect the others.