Split a list into two parts based on a filter?
Tim Chase
python.list at tim.thechases.com
Mon Jun 10 19:10:22 EDT 2013
On 2013-06-11 08:50, Chris Angelico wrote:
> The iterator version strikes my fancy. Maybe this isn't of use to
> you, but I'm going to try my hand at making one anyway.
>
> >>> def iterpartition(pred,it):
> """Partition an iterable based on a predicate.
>
> Returns two iterables, for those with pred False and those
> True.""" falses,trues=[],[]
This is really nice. I think the only major modification I'd make is
to use a collections.deque() instead of lists here:
trues, falses = collections.deque(), collections.deque()
as I seem to recall that list.pop(0) has some performance issues if
it gets long, while the deque is optimized for fast (O(1)?) push/pop
on either end.
-tkc
More information about the Python-list
mailing list