Can anyone please explain what is happening here? I understand python ints are assigned by value (and not by reference).
>>> alist = [1,2,3]
>>> a = [[0]*3]*4
>>> a[0][0] = len(alist)
>>> alist.append(1)
>>> a[1][0] = len(alist)
>>> a[0][0]a
4
>>>
When you create a list using the * notation, you're repeating the same element. Not copies of the element, but the same exact object.
When the object you're repeating is immutable, such as an integer, you won't notice.
When the object is mutable, such as a list, you get the same list repeated. If you make a change to one list you're making it to all of them.
In your case you made a change to element [1] and it was reflected in element [0].
The problem is that your outer list contains multiple copies of the same inner list value. Here's how you can tell:
a = [[0]*3]*4
print(a[0] is a[1]) # prints True
If you want a two dimensional list of zeros, I suggest using a list comprehension for the outer part so that you get separate inner lists instances:
a = [[0]*3 for _ in range(4)]
print(a[0] is a[1]) # prints False
a[0][0]=1
print(a[1][0]) # prints 0
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