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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With