Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python [0]*n syntax works only on immutable object?

Tags:

python

list

a = [[0]*3] * 4
print(a[0] is a[1]) # True

when I initialize a two dimensional array that way, things went wrong. Took me a bit time to find this unexpected behavior. So is this syntax only work on immutable object?

like image 683
Alex Kai Avatar asked Jan 19 '26 04:01

Alex Kai


1 Answers

It "worked" in your example too, in its way. This is just how the implementation of list.__mul__ interprets what you want. The list can't construct new objects, it doesn't know how to create new objects from whatever objects it happens to contain. It expands itself with new references to those objects.

You get the same behavior with immutable integers

>>> x = [0] * 3
>>> x[0] is x[1]
True

You can get the two dimensional array with

>>> a = [[0]*3 for _ in range(4)]
>>> a[0] is a[1]
False

The reason why [0] * 3 does what you want is that it is creating list that contains 3 references to the same immutable 0.

like image 143
tdelaney Avatar answered Jan 21 '26 16:01

tdelaney



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!