简体   繁体   中英

What does [[]]*2 do in python?

A = [[]]*2

A[0].append("a")
A[1].append("b")

B = [[], []]

B[0].append("a")
B[1].append("b")

print "A: "+ str(A)
print "B: "+ str(B)

Yields:

A: [['a', 'b'], ['a', 'b']]
B: [['a'], ['b']]

One would expect that the A list would be the same as the B list, this is not the case, both append statements were applied to A[0] and A[1].

Why?

A = [[]]*2 creates a list with 2 identical elements: [[],[]] . The elements are the same exact list. So

A[0].append("a")
A[1].append("b")

appends both "a" and "b" to the same list.

B = [[], []] creates a list with 2 distinct elements.

In [220]: A=[[]]*2

In [221]: A
Out[221]: [[], []]

This shows that the two elements of A are identical:

In [223]: id(A[0])==id(A[1])
Out[223]: True

In [224]: B=[[],[]]

This shows that the two elements of B are different objects.

In [225]: id(B[0])==id(B[1])
Out[225]: False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM