On Mon, 6 Jun 2022 at 18:22, Paul Moore <p.f.mo...@gmail.com> wrote: > > There’s an itertools recipe, “partition”. >
Yes, there is (and plenty of equivalents in other languages). But it's still not what I'd call "particularly easy". What that recipe does is filter the same iterable with the same predicate twice, so it depends on the predicate being repeatable. You can't use it, for instance, to split a data set into training and test sets, even though conceptually this should work: training, test = partition(lambda x: random.random() < 0.9, dataset) To truly perform a one-pass partitioning operation, you'd have to do something like this: def partition(pred, iter): results = [], [] for thing in iter: results[not pred(thing)].append(thing) return results Obviously that works only on finite iterables, so it's not appropriate for an itertools recipe, but it does guarantee that the predicate is called once per item and each item ends up in precisely one list. It would be kinda nice to be able to do something like this with a comprehension, since there's a fair bit of overhead to calling a function (predicate functions have to be called for each element, but a comprehension wraps everything up into one function). But since it's not, the above is good enough for the cases where it's needed - not particularly easy, but not all that hard either. ChrisA _______________________________________________ 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/BUFIMKKIJOPJQQ4WT2VLNXTTLAPQGCIN/ Code of Conduct: http://python.org/psf/codeofconduct/