Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a[] and a[:] when assigning values?

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?

like image 367
can. Avatar asked Dec 08 '22 17:12

can.


1 Answers

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.

like image 157
Gareth Latty Avatar answered Dec 11 '22 07:12

Gareth Latty