Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LISTS in python anamolous behavior with reference to single dimension lists

Tags:

python

list

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

like image 532
Aman Oswal Avatar asked Mar 04 '23 00:03

Aman Oswal


1 Answers

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.

like image 195
juanpa.arrivillaga Avatar answered Mar 05 '23 16:03

juanpa.arrivillaga