list.without()?

Hrvoje Niksic hniksic at iskon.hr
Tue Nov 16 04:44:05 EST 1999


mlh at vier.idi.ntnu.no (Magnus L. Hetland) writes:

> Is there a function or method in the standard language that can
> non-destructively return a list without a specified element?

What's wrong with destructively removing the element from a copy?  It
will be faster than using `filter' and friends as other proposed, and
guaranteed to work.  In fact, (shallow) copying is the pretty much
standard way of turning any destructive operation non-destructive.

If you want it bundled in a function, you can do this:

def without(list, element):
    copy = self[:]
    copy.remove(element)
    return copy

If you want to use classes, you can inherit from UserList.

If your only problem with this approach is having a temporary
variable, then you don't need to lobby for adding a new method -- you
can simply lobby for the `remove()' method to return self.  In that
case, you could write:

    newlist = somelist[:].remove(element)

Or, for that matter:

    newlist = somelist[:].sort()

Or:

    for elem in dict.keys().sort():
        ...

But neither is likely to be successful.  Adding a new builtin method
for a task that can be accomplished with two lines of code doesn't
sound promising.  And the destructive methods rarely return self, "to
remind you [that they modify the list in place]."




More information about the Python-list mailing list