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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With