0

I append expand a list using operator ' * '.

>>> A = [[0, 0]] * 2
>>> A
[[0, 0], [0, 0]]

When I am trying to modify the first element in first list item, it modified the first element in all items of the list.

>>> A[0][0] = 10
>>> A
[[10, 0], [10, 0]]

Could you help me explain why? What is the mechanism behind?

hugle
  • 145
  • 1
  • 5

2 Answers2

2

Multiply creates a copy of the reference, not the object. The reference is similar to a pointer in C, both references point to the same object in memory, but there's only one copy of that object.

If you want to create copies of that object, do the following:

A = [[0, 0] for _ in range(2)]

This is a generator expression, and python will "run" the iterations therefore creating a new element each time.

simonzack
  • 19,729
  • 13
  • 73
  • 118
1

A contains two references to the same list. What you do is essentially the same as

AA = [0, 0]
A = [AA, AA]

so a modification of A[0], A[1] and AA is equivalent.

Workaround:

A = [[0, 0], [0, 0]]

or, as written in simonzack's answer,

A = [[0, 0] for _ in range(2)]
Community
  • 1
  • 1
glglgl
  • 89,107
  • 13
  • 149
  • 217