What is the difference between [] and [:] when assigning values?

I see this piece of code:

a = [] a = [a, a, None] # makes a = [ [], [], None] when print a = [] a[:] = [a, a, None] # makes a = [ [...], [...], None] when print 

It seems that assigning a[:] assigns a pointer, but I cannot find documents about it. So can anyone give me an explicit explanation?

+4
source share
3 answers

In Python, a is a name - it points to an object, in this case a list.

In the first example, a first points to an empty list, and then to a new list.

In your second example, a points to an empty list, then it is updated to contain values ​​from the new list. This does not change the list of a links.

The difference in the final result is that, since the right-hand side of the operation is first evaluated, in both cases a points to the original list. This means that in the first case, it points to a list that was previously a , and in the second case, it points to itself, creating a recursive structure.

If you have trouble understanding this, I recommend taking a look at which he visualized .

+7
source

The first will point a to a new object, the second will mutate a , so the list that a refers to remains the same.

For instance:

 a = [1, 2, 3] b = a print b # [1, 2, 3] a[:] = [3, 2, 1] print b # [3, 2, 1] a = [1, 2, 3] #b still references to the old list print b # [3, 2, 1] 
+7
source

A clearer example from @pythonm's answer

 >>> a=[1,2,3,4] >>> b=a >>> c=a[:] >>> a.pop() 4 >>> a [1, 2, 3] >>> b [1, 2, 3] >>> c [1, 2, 3, 4] >>> 
0
source

All Articles