9
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?

NorthIsUp
  • 17,502
  • 9
  • 29
  • 35
  • There's a very nice explanation of Python's * operator for list's in this thread: http://stackoverflow.com/questions/974931/multiply-operator-applied-to-listdata-structure – Justin Ardini Jul 02 '10 at 01:19
  • 7
    @S. Lott: It seems quite clear to me: two very similar forms, [[]]*2 and [[],[]] yield very different results when operated upon in the same way. Why? – Owen S. Jul 02 '10 at 01:31

1 Answers1

17

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
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677