How to clear a list (3 ways).

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Mar 7 15:49:39 CET 2008


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

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




More information about the Python-list mailing list