Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 378
NorthIsUp Avatar asked Jul 02 '10 01:07

NorthIsUp


1 Answers

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
like image 140
unutbu Avatar answered Sep 20 '22 16:09

unutbu