> I know that the standard idioms for clearing a list are:
> 
>   (1) mylist[:] = []
>   (2) del mylist[:]
> 
> I guess I'm not in the "slicing frame of mind", as someone put it, but 
> can someone explain what the difference is between these and:
> 
>   (3) mylist = []
> 
> Why are (1) and (2) preferred? I think the first two are changing the 
> list in-place, but why is that better? Isn't the end result the same?

A little example will demonstrate:

        >>> x = [1,2,3,4,5]
        >>> y = x
        >>> z = x
        >>> x = []
        >>> y
        [1, 2, 3, 4, 5]
*       >>> z
        [1, 2, 3, 4, 5]
        >>> y[:]=[]
*       >>> z
        []

[*] note the differences in the results of "z", even though we've 
never touched "z" explicitly

By using

        x = []

you set x, but you do not clear the list that other items (y & z) 
reference.  If you use either of the two idioms you describe, you 
effect all items that reference that list.

-tim




-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to