On 2022-06-07 11:03, Chris Angelico wrote:
On Tue, 7 Jun 2022 at 19:09, Ben Rudiak-Gould <benrud...@gmail.com> wrote:

This calls the predicate once per element:

    def partition(pred, iterable):
        t1, t2 = tee((pred(x), x) for x in iterable)
        return (x for b, x in t1 if not b), (x for b, x in t2 if b)

It's kind of inefficient though.

Honestly, if it weren't that there's currently a recipe in itertools,
I think the list-based version would be the best recipe to offer. The
cost of doing the job lazily AND maintaining all the other
expectations is too high; if you really need it to be lazy, it's
probably worth seeing if one of the other demands can be relaxed (eg
if it's fine to call the predicate twice).

For the OP's task, doing the partitioning eagerly wouldn't be an issue.

The problem with a lazy solution is that if you're producing 2 streams of output, as it were, and if you're consuming from only one of them, what are you going to do about the other one? You still need to store the items for it in case you want to consume them later, and if the original iterable is infinite, you have a problem...
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/T3JM5DZSN55OEWINS2HYJAZJLOKLJWPJ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to