Reading the Python 3.2 tutorial here, towards the end one of the examples is
a[:] = []
Is this equivalent to
a = []
? If it is, why did they write a[:]
instead of a
? If it isn't, what is the difference?
Reading the Python 3.2 tutorial here, towards the end one of the examples is
a[:] = []
Is this equivalent to
a = []
? If it is, why did they write a[:]
instead of a
? If it isn't, what is the difference?
They are not equivalent. These two examples should get you to understand the difference.
Example 1:
>>> b = [1,2,3]
>>> a = b
>>> a[:] = []
>>> print b
[]
Example 2:
>>> b = [1,2,3]
>>> a = b
>>> a = []
>>> print b
[1,2,3]
That is explained, as you would expect, right there were they use it:
This means that the following slice returns a shallow copy of the list a
The second line doesn't modify the list, it simply arranges for a
to point to a new, empty, list. The first line modifies the list pointed at by a. Consider this sample seesion in the python interpreter:
>>> b=[1,2,3]
>>> a=b
>>> a[:]=[]
>>> a
[]
>>> b
[]
Both a
and b
point to the same list, so we can see that a[:]=[]
empties the list and now both a
and b
point to the same empty list.