python 列表中 [[], [], []] 和 3*[[]]差异

问:

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]]

posted @ 2017-07-06 10:25  吴增丁  阅读(541)  评论(0编辑  收藏  举报