hniksic at iskon.hr
Tue Nov 16 10:44:05 CET 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[:]
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()
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