Splitting lists

Alex Martelli aleax at aleax.it
Thu Feb 27 13:07:35 EST 2003


A. Lloyd Flanagan wrote:

> "Ferenczi Viktor" <cx at cx.hu> wrote in message
> news:<mailman.1046321293.2733.python-list at python.org>...
>> Are there any fast, simple and elegant method to split a list by a filter
>> function?
>> 
> 
> Here's another interesting approach.  I have no idea of the
> performance implications, but since Set is hashed it might help:

I doubt it will have optimal performance, because internally it's
still doing two loops on the input list x, but it can still be of
interest IF you don't care about the order of things in your
list (Set, like dict, doesn't care about items' order).


> from sets import Set
> def fn(e):
>     return e < 5
> 
> x = Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
> y = Set(filter(fn, x))
> z = x - y
> print y
> print z
> 
> y = Set([1, 2, 3, 4])
> z = Set([5, 6, 7, 8, 9, 10])
> 
> Of course this won't work on older python versions, or if your list
> contains mutable objects.

For Python versions < 2.3, you can just use dict directly, although
less elegantly -- e.g., to get list results (but not in order...):

y = dict( [(item,1) for item in x if fn(item)] )
z = [item for item in x if item not in y]
y = y.keys()


Alex





More information about the Python-list mailing list