Split a list into two parts based on a filter?

Chris Angelico rosuav at gmail.com
Mon Jun 10 19:12:58 EDT 2013


On Tue, Jun 11, 2013 at 9:10 AM, Tim Chase
<python.list at tim.thechases.com> wrote:
> 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.

Sure. If it's that good I might submit it to more-itertools... heh.

ChrisA



More information about the Python-list mailing list