How to clear a list (3 ways).

John Machin sjmachin at lexicon.net
Fri Mar 7 17:12:13 EST 2008


On Mar 8, 1:49 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
> En Fri, 07 Mar 2008 09:39:05 -0200, <francois.petitj... at bureauveritas.com>
> escribi�:
>
> > Executive summary : What idiom do you use for resetting a list ?
> >    lst = |]  # (1)
> >    lst[:] = []  #  (2)
> >    del lst[:]  #  (3)
>
> (3) if I want to keep the same list else (1)

"resetting a list" is vague and dubious terminology.

(1) abandons a reference to some object (which MAY be a list) and
binds the name "lst" to a new empty list.

(3) providing that the referred-to object is of a type that supports
assigning to slices, removes the contents.

(2) effects the same as (3) -- it's just slower to type, compile and
execute.

I would rewrite the advice to the OP as:

Use (3) if and only if you have a justifiable need (not "want") to
keep the same list.

Cheers,
John



More information about the Python-list mailing list