[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: How to clear a list (3 ways).

Gabriel Genellina

3/7/2008 2:50:00 PM

En Fri, 07 Mar 2008 09:39:05 -0200, <francois.petitjean@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)

An example when (1) is desirable:

# generate lines of text not exceeding 40 chars
# yields a list of words forming a line
def gen_lines(words):
line = []
width = 0
for word in words:
if width + len(word) + 1 > 40:
yield line # <<<
del line[:] # <<<
width = 0
line.append(word)
width += len(word) + 1
yield line

import string
words = string.__doc__.split() # some text
lines = list(gen_lines(words))
print lines
[['considered', 'printable'], ['considered', 'printable'], ['considered',
'print
able'], ['considered', 'printable'], ['considered', 'printable'], ...

In this case, yielding always the same object isn't a good idea if the
consumer doesn't process it immediately. Changing the generator function
to use the method (1) gives the expected result (or, one could say,
lessens the coupling between the generator and its consumer).

--
Gabriel Genellina

1 Answer

John Machin

3/7/2008 10:12:00 PM

0

On Mar 8, 1:49 am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar> wrote:
> En Fri, 07 Mar 2008 09:39:05 -0200, <francois.petitj...@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