clear derived list

Jp Calderone exarkun at intarweb.us
Tue Mar 11 18:39:11 EST 2003


On Tue, Mar 11, 2003 at 05:08:26PM -0600, John Hunter wrote:
> 
> I have a class derived from a list.  I want to be able to set the list
> from another list, first clearing the existing members.  I don't see
> an analog to the clear method of dictionaries.
> 
> Here is what I am doing now
> 
> class mylist(list):
>     def set(self, seq):
>         # flush the old list
>         [self.pop() for i in range(len(self))]
>         self.extend(seq)

  Aside from the obvious problem, I want to point out that this is a
terrible abuse of list comprehensions.  This is not the point.  A good rule
of thumb is that if you're not storing the result of a list comprehension,
you should -not- be using a list comprehension.

  Now, here are a couple alternatives:

    del self[:]
    self.extend(seq)

  or

    self[:] = seq

  Jp

-- 
A disciple of another sect once came to Drescher as he was eating his
morning meal. "I would like to give you this personality test," said the
outsider, "because I want you to be happy." Drescher took the paper that was
offered him and put it into the toaster: "I wish the toaster to be happy, 
too."
-- 
 up 8 days, 15:59, 8 users, load average: 0.22, 0.13, 0.04





More information about the Python-list mailing list