问:
What's the difference between "[[], [], []]" and "3*[[]]" ?
答:
[[], [], []] makes a list containing references to three different lists. 3*[[]] makes a list with three references to the *same* list
这点差别可以让你出现意想不到的错误!如下:
第一种情况:
>>> l = [[],[],[]]
>>> l
[[], [], []]
>>> for i in range(3):
l[i].append(i)
>>> l
[[0], [1], [2]]
第二种情况:
>>> l = 3*[[]]
>>> l
[[], [], []]
>>> for i in range(3):
l[i].append(i)
>>> l
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]