0

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?

Randomblue
  • 112,777
  • 145
  • 353
  • 547

3 Answers3

7

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]
Charles Beattie
  • 5,739
  • 1
  • 29
  • 32
1

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

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

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.

Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88