0

Could somebody please explain the following behaviour?

X=2*[[]]
print X
X[0].append(1)
print X

yields

[[], []]
[[1], [1]]

I would expect the last list to be [[1], []]. Indeed, the following

X=[[],[]]
print X
X[0].append(1)
print X

yields

[[], []]
[[1], []]

Why this difference?

geo909
  • 394
  • 1
  • 6
  • 18

1 Answers1

5

The multiplication syntax you used creates a shallow copy of the contents. Each list element within will be a new reference to the same list.

The second example you give actually produces a list of two different lists.

y = 2*[x]

is roughly equivalent to doing

y = [x] + [x]

The x in both places refers to the same list.

>>> y = 2*[[]]
>>> y[0].append(1)
>>> y
[[1], [1]]
>>> x = []
>>> y = [x] + [x]
>>> y
[[], []]
>>> y[0].append(1)
>>> y
[[1], [1]]

To create a list that functions as your second example, try

>>> y=[[] for n in range(2)]
>>> y[0].append(1)
>>> y
[[1], []]
geo909
  • 394
  • 1
  • 6
  • 18
Brian
  • 3,091
  • 16
  • 29