2017-08-23 79 views
2
怪時列表行爲

有人能解釋爲什麼:的Python:初始化空巢列表

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 

+0

[列表變化列表反映跨過子列表意外](HTTPS(在Python 3.6.1測試):// stackoverflow.com/q/240178/2301450) – vaultah

回答

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