4
a = [0]*4
a[0]= 1
print(a)

Output is [1,0,0,0] while it should be [1,1,1,1] according to the behavior of lists explained in Strange behavior of lists in python which says that * creates references to the object and not copy of values. Please explain

Aman Oswal
  • 49
  • 5
  • 1
    C.f. `a = [[0]] * 4; a[0][0] = 1` – wjandrea Dec 27 '19 at 04:16
  • Replicating a number does not have the same problems as replicating a list (or other mutable object). You can't change a number in-place, you can only replace it. – hpaulj Dec 27 '19 at 04:17

1 Answers1

7

Yes, using the repetition operator, *, creates multiple references to the objects in the list. However, a[0] = 1 does not modify those objects, it modifies the list.

If you could modify the objects in the list (you cannot, in this case, because int objects are immutable), and then you did modify those objects, then you would see the same behavior.

Note, even if you use a[0] = <something> with mutable objects, it won't behave that way:

>>> x = [[]]*3
>>> x
[[], [], []]
>>> x[0] = [1] # modify the list
>>> x
[[1], [], []]

You have to actually modify the object inside the list:

>>> x = [[]]*3
>>> x
[[], [], []]
>>> x[0].append(1) # modify the in the list
>>> x
[[1], [1], [1]]

The fundamental distinction you are missing is the difference between modifying the list itself versus the objects inside the list.

Note, also, list objects do not have a dimension.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172