0

List comprehension is pretty good for filtering a list. Is there a good way of obtaining the other half, the filtered-out part in a single pass? For example; take this example list:

>>> a = [5, 10, 45, 99]

The following operation selects some values from that list:

>>> b = [x for x in a if somecondition(x)]
>>> b
>>> [10, 45]

But then again, I also need the other half, so I seek something like:

>>> (b, c) = divideintotwo(x, somecondition)
>>> b
>>> [10, 45]
>>> c
>>> [5, 99]

I can write this function by myself. Though, I would rather use the one that exists, if there exists. Seems a little too basic to not have one, when Python has almost everything built-in.

Utkan Gezer
  • 3,009
  • 2
  • 16
  • 29
  • 4
    See `John La Rooy` answer in http://stackoverflow.com/questions/949098/python-split-a-list-based-on-a-condition – Arunmu Jun 04 '16 at 15:55
  • Thank you. I couldn't find any results to my searches. So I guess there still is no such function after 7 years. – Utkan Gezer Jun 04 '16 at 16:00
  • This is something which can be `composed` using an existing function in exactly 2 lines of code..you still need it to be part of standard library ? :) – Arunmu Jun 04 '16 at 16:35
  • @Arunmu Yes, I do. The alternative takes twice as long. I have written the function myself. – Utkan Gezer Jun 04 '16 at 19:17

0 Answers0