I happen to see this snippet of code:
a = []
a = [a, a, None]
# makes a = [ [], [], None] when print
a = []
a[:] = [a, a, None]
# makes a = [ [...], [...], None] when print
It seems the a[:]
assignment assigns a pointer but I can't find documents about that. So anyone could give me an explicit explanation?
In Python, a
is a name - it points to an object, in this case, a list.
In your first example, a
initially points to the empty list, then to a new list.
In your second example, a
points to an empty list, then it is updated to contain the values from the new list. This does not change the list a
references.
The difference in the end result is that, as the right hand side of an operation is evaluated first, in both cases, a
points to the original list. This means that in the first case, it points to the list that used to be a
, while in the second case, it points to itself, making a recursive structure.
If you are having trouble understanding this, I recommend taking a look at it visualized.
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