简体   繁体   中英

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?

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 .

The first will point a to a new object, the second will mutate a , so the list referenced by a is still the same.

For example:

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]

More clear example from @pythonm response

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM