Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lists of lists: why does changing value at a[1][0] also change a[0][0]? [duplicate]

Tags:

python

list

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
>>> 
like image 633
Jules Testard Avatar asked Jan 25 '26 21:01

Jules Testard


2 Answers

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].

like image 121
Mark Ransom Avatar answered Jan 27 '26 12:01

Mark Ransom


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
like image 34
Blckknght Avatar answered Jan 27 '26 10:01

Blckknght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!