Python:初始化空嵌套列表时的奇怪列表行为

时间:2017-08-23 12:52:59

标签: python python-3.x list

有人可以解释原因:

b = 10*[[]]
b[0].append(3)

b现在是:

[[3], [3], [3], [3], [3], [3], [3], [3], [3], [3]]

但如果我这样做:

b = [[] for _ in range(10)]
b[0].append(3)

b现在是:

[[3], [], [], [], [], [], [], [], [], []]

另请注意

10*[[]] == [[] for [] in range(10)]

返回

True

(在Python 3.6.1中测试)

1 个答案:

答案 0 :(得分:3)

 because:
    >>> b = 10*[[]]
    >>> b[0] is b[1]
    True
    >>> b = [[] for _ in range(10)]
    >>> b[0] is b[1]
    False
    >>>