[Tutor] Python3 Tutorial question about a[:] = []

Richard D. Moores rdmoores at gmail.com
Wed Feb 16 19:45:25 CET 2011


On Wed, Feb 16, 2011 at 09:50, Brett Ritter <swiftone at swiftone.org> wrote:
> On Wed, Feb 16, 2011 at 12:39 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>> from <http://docs.python.org/py3k/tutorial/introduction.html#lists> :
>>
>>>>> # Clear the list: replace all items with an empty list
>>>>> a[:] = []
>>>>> a
>> []
>>
>> I've been using
>>>>> a = []
>>>>> a
>> []
>>
>> What's the difference?
>
> a = []
>
> This sets the variable "a" to refer to a new list
>
> a[:] = []
>
> This replaces the existing content of a with empty contents.
>
> Check out this example in interactive mode
>
>>>> a = [1,2,3]
>>>> b = a
>>>> a = []
>>>> print a
> []
>>>> print b
> [1, 2, 3]
>
>
> Versus:
>
>>>> a = [1,2,3]
>>>> b = a
>>>> a[:] = []
>>>> print a
> []
>>>> print b
> []

Ah, got it!

Thanks very much.

Dick


More information about the Tutor mailing list