Is there a way to “fork” a list in two based on a condition [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP








up vote
13
down vote

favorite
1













This question already has an answer here:



  • Python: split a list based on a condition?

    26 answers



I have seen a pattern repeated a couple times in my team's code, it looks like this



numbers = [1, 2, 3, 4]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]


I was wondering if there is a function somewhere (I have looked around but haven't been able to find it) that would do something like this



numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = fork(numbers, lambda x: x % 2 == 0)


So, this function I am looking for, would receive an iterable and a function, and return two lists, one would be the values that match a provided condition, and the other would be the ones that didn't.



Is there something around python's standard library that achieves this?










share|improve this question















marked as duplicate by Aran-Fey python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Aug 8 at 11:16


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 10




    Normally this is called a "partition", there's a recipe in itertools for it.
    – jonrsharpe
    Aug 8 at 9:09














up vote
13
down vote

favorite
1













This question already has an answer here:



  • Python: split a list based on a condition?

    26 answers



I have seen a pattern repeated a couple times in my team's code, it looks like this



numbers = [1, 2, 3, 4]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]


I was wondering if there is a function somewhere (I have looked around but haven't been able to find it) that would do something like this



numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = fork(numbers, lambda x: x % 2 == 0)


So, this function I am looking for, would receive an iterable and a function, and return two lists, one would be the values that match a provided condition, and the other would be the ones that didn't.



Is there something around python's standard library that achieves this?










share|improve this question















marked as duplicate by Aran-Fey python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Aug 8 at 11:16


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 10




    Normally this is called a "partition", there's a recipe in itertools for it.
    – jonrsharpe
    Aug 8 at 9:09












up vote
13
down vote

favorite
1









up vote
13
down vote

favorite
1






1






This question already has an answer here:



  • Python: split a list based on a condition?

    26 answers



I have seen a pattern repeated a couple times in my team's code, it looks like this



numbers = [1, 2, 3, 4]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]


I was wondering if there is a function somewhere (I have looked around but haven't been able to find it) that would do something like this



numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = fork(numbers, lambda x: x % 2 == 0)


So, this function I am looking for, would receive an iterable and a function, and return two lists, one would be the values that match a provided condition, and the other would be the ones that didn't.



Is there something around python's standard library that achieves this?










share|improve this question
















This question already has an answer here:



  • Python: split a list based on a condition?

    26 answers



I have seen a pattern repeated a couple times in my team's code, it looks like this



numbers = [1, 2, 3, 4]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]


I was wondering if there is a function somewhere (I have looked around but haven't been able to find it) that would do something like this



numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = fork(numbers, lambda x: x % 2 == 0)


So, this function I am looking for, would receive an iterable and a function, and return two lists, one would be the values that match a provided condition, and the other would be the ones that didn't.



Is there something around python's standard library that achieves this?





This question already has an answer here:



  • Python: split a list based on a condition?

    26 answers







python list






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 8 at 9:10









jonrsharpe

74.8k1089189




74.8k1089189










asked Aug 8 at 9:08









Jose Enrique Narvaez

744




744




marked as duplicate by Aran-Fey python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Aug 8 at 11:16


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by Aran-Fey python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Aug 8 at 11:16


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









  • 10




    Normally this is called a "partition", there's a recipe in itertools for it.
    – jonrsharpe
    Aug 8 at 9:09












  • 10




    Normally this is called a "partition", there's a recipe in itertools for it.
    – jonrsharpe
    Aug 8 at 9:09







10




10




Normally this is called a "partition", there's a recipe in itertools for it.
– jonrsharpe
Aug 8 at 9:09




Normally this is called a "partition", there's a recipe in itertools for it.
– jonrsharpe
Aug 8 at 9:09












6 Answers
6






active

oldest

votes

















up vote
11
down vote



accepted










I usually call this sift, but partition is fine too.



Another, itertools-less implementation might be



def sift(iterable, predicate):
t =
f =
for value in iterable:
(t if predicate(value) else f).append(value)
return (t, f)

even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)


EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):



def sift2(iterable, predicate):
t =
f =
ta = t.append
fa = f.append
for value in iterable:
(ta if predicate(value) else fa)(value)
return (t, f)





share|improve this answer






















  • I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
    – Jose Enrique Narvaez
    Aug 8 at 9:25











  • using timeit suggests this takes quite a bit longer than the original approach for a list of 1000 items. %timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) vs %timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each) though it does have an additional function call
    – roganjosh
    Aug 8 at 9:56











  • @roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
    – AKX
    Aug 8 at 10:00










  • @AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
    – roganjosh
    Aug 8 at 10:01







  • 1




    @roganjosh I also added a 30% faster implementation. :)
    – AKX
    Aug 8 at 10:04

















up vote
3
down vote













You can use the following function:



from itertools import filterfalse, tee

def fork(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
t1, t2 = tee(iterable)
return list(filterfalse(pred, t1)), list(filter(pred, t2))


Source: itertools






share|improve this answer



























    up vote
    2
    down vote













    I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:



    def myFunc(iterable, func):

    first = [i for i in iterable if func(i)]
    second = [i for i in iterable if not func(i)]

    return first,second


    numbers = [1, 2, 3, 4]
    even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)

    print(even_numbers) # [2, 4]
    print(odd_numbers) # [1, 3]





    share|improve this answer



























      up vote
      2
      down vote













      Full code following @jonrsharpe suggestion.



      import itertools

      def fork(iterable):
      "Returns list of even, odd elements of a list"
      t1, t2 = itertools.tee(iterable)
      pred = lambda i: i % 2 == 0
      return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))

      odd, even = fork([1,2,3,4,5])
      print(odd)
      print(even)


      Alternative numpy version which might be faster for big arrays



      import numpy as np

      def fork(iterable):
      "Returns array of even, odd elements of an array"
      iterable_array = np.asarray(iterable)
      mask = (iterable_array % 2 == 0)
      return iterable_array[~mask], iterable_array[mask]





      share|improve this answer





























        up vote
        2
        down vote













        The simplest possible implementation would be probably



        def partition(xs, cond):
        res = ,
        for x in xs:
        res[not cond(x)].append(x)
        return res





        share|improve this answer




















        • Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
          – roganjosh
          Aug 8 at 10:17











        • @roganjosh: sure, that's easy to optimize if needed
          – georg
          Aug 8 at 10:19

















        up vote
        0
        down vote













        You can create your own function:



        l = [1, 2, 3, 4]
        def fork(l,key):
        return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
        even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
        print(even_numbers)
        print(odd_numbers)


        Output:



        [2, 4]
        [1, 3]





        share|improve this answer



























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          11
          down vote



          accepted










          I usually call this sift, but partition is fine too.



          Another, itertools-less implementation might be



          def sift(iterable, predicate):
          t =
          f =
          for value in iterable:
          (t if predicate(value) else f).append(value)
          return (t, f)

          even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)


          EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):



          def sift2(iterable, predicate):
          t =
          f =
          ta = t.append
          fa = f.append
          for value in iterable:
          (ta if predicate(value) else fa)(value)
          return (t, f)





          share|improve this answer






















          • I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
            – Jose Enrique Narvaez
            Aug 8 at 9:25











          • using timeit suggests this takes quite a bit longer than the original approach for a list of 1000 items. %timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) vs %timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each) though it does have an additional function call
            – roganjosh
            Aug 8 at 9:56











          • @roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
            – AKX
            Aug 8 at 10:00










          • @AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
            – roganjosh
            Aug 8 at 10:01







          • 1




            @roganjosh I also added a 30% faster implementation. :)
            – AKX
            Aug 8 at 10:04














          up vote
          11
          down vote



          accepted










          I usually call this sift, but partition is fine too.



          Another, itertools-less implementation might be



          def sift(iterable, predicate):
          t =
          f =
          for value in iterable:
          (t if predicate(value) else f).append(value)
          return (t, f)

          even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)


          EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):



          def sift2(iterable, predicate):
          t =
          f =
          ta = t.append
          fa = f.append
          for value in iterable:
          (ta if predicate(value) else fa)(value)
          return (t, f)





          share|improve this answer






















          • I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
            – Jose Enrique Narvaez
            Aug 8 at 9:25











          • using timeit suggests this takes quite a bit longer than the original approach for a list of 1000 items. %timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) vs %timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each) though it does have an additional function call
            – roganjosh
            Aug 8 at 9:56











          • @roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
            – AKX
            Aug 8 at 10:00










          • @AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
            – roganjosh
            Aug 8 at 10:01







          • 1




            @roganjosh I also added a 30% faster implementation. :)
            – AKX
            Aug 8 at 10:04












          up vote
          11
          down vote



          accepted







          up vote
          11
          down vote



          accepted






          I usually call this sift, but partition is fine too.



          Another, itertools-less implementation might be



          def sift(iterable, predicate):
          t =
          f =
          for value in iterable:
          (t if predicate(value) else f).append(value)
          return (t, f)

          even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)


          EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):



          def sift2(iterable, predicate):
          t =
          f =
          ta = t.append
          fa = f.append
          for value in iterable:
          (ta if predicate(value) else fa)(value)
          return (t, f)





          share|improve this answer














          I usually call this sift, but partition is fine too.



          Another, itertools-less implementation might be



          def sift(iterable, predicate):
          t =
          f =
          for value in iterable:
          (t if predicate(value) else f).append(value)
          return (t, f)

          even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)


          EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):



          def sift2(iterable, predicate):
          t =
          f =
          ta = t.append
          fa = f.append
          for value in iterable:
          (ta if predicate(value) else fa)(value)
          return (t, f)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Aug 8 at 10:04

























          answered Aug 8 at 9:23









          AKX

          37.1k34964




          37.1k34964











          • I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
            – Jose Enrique Narvaez
            Aug 8 at 9:25











          • using timeit suggests this takes quite a bit longer than the original approach for a list of 1000 items. %timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) vs %timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each) though it does have an additional function call
            – roganjosh
            Aug 8 at 9:56











          • @roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
            – AKX
            Aug 8 at 10:00










          • @AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
            – roganjosh
            Aug 8 at 10:01







          • 1




            @roganjosh I also added a 30% faster implementation. :)
            – AKX
            Aug 8 at 10:04
















          • I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
            – Jose Enrique Narvaez
            Aug 8 at 9:25











          • using timeit suggests this takes quite a bit longer than the original approach for a list of 1000 items. %timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) vs %timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each) though it does have an additional function call
            – roganjosh
            Aug 8 at 9:56











          • @roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
            – AKX
            Aug 8 at 10:00










          • @AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
            – roganjosh
            Aug 8 at 10:01







          • 1




            @roganjosh I also added a 30% faster implementation. :)
            – AKX
            Aug 8 at 10:04















          I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
          – Jose Enrique Narvaez
          Aug 8 at 9:25





          I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
          – Jose Enrique Narvaez
          Aug 8 at 9:25













          using timeit suggests this takes quite a bit longer than the original approach for a list of 1000 items. %timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) vs %timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each) though it does have an additional function call
          – roganjosh
          Aug 8 at 9:56





          using timeit suggests this takes quite a bit longer than the original approach for a list of 1000 items. %timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) vs %timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each) though it does have an additional function call
          – roganjosh
          Aug 8 at 9:56













          @roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
          – AKX
          Aug 8 at 10:00




          @roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
          – AKX
          Aug 8 at 10:00












          @AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
          – roganjosh
          Aug 8 at 10:01





          @AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
          – roganjosh
          Aug 8 at 10:01





          1




          1




          @roganjosh I also added a 30% faster implementation. :)
          – AKX
          Aug 8 at 10:04




          @roganjosh I also added a 30% faster implementation. :)
          – AKX
          Aug 8 at 10:04












          up vote
          3
          down vote













          You can use the following function:



          from itertools import filterfalse, tee

          def fork(pred, iterable):
          'Use a predicate to partition entries into false entries and true entries'
          t1, t2 = tee(iterable)
          return list(filterfalse(pred, t1)), list(filter(pred, t2))


          Source: itertools






          share|improve this answer
























            up vote
            3
            down vote













            You can use the following function:



            from itertools import filterfalse, tee

            def fork(pred, iterable):
            'Use a predicate to partition entries into false entries and true entries'
            t1, t2 = tee(iterable)
            return list(filterfalse(pred, t1)), list(filter(pred, t2))


            Source: itertools






            share|improve this answer






















              up vote
              3
              down vote










              up vote
              3
              down vote









              You can use the following function:



              from itertools import filterfalse, tee

              def fork(pred, iterable):
              'Use a predicate to partition entries into false entries and true entries'
              t1, t2 = tee(iterable)
              return list(filterfalse(pred, t1)), list(filter(pred, t2))


              Source: itertools






              share|improve this answer












              You can use the following function:



              from itertools import filterfalse, tee

              def fork(pred, iterable):
              'Use a predicate to partition entries into false entries and true entries'
              t1, t2 = tee(iterable)
              return list(filterfalse(pred, t1)), list(filter(pred, t2))


              Source: itertools







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Aug 8 at 9:22









              stasdeep

              669414




              669414




















                  up vote
                  2
                  down vote













                  I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:



                  def myFunc(iterable, func):

                  first = [i for i in iterable if func(i)]
                  second = [i for i in iterable if not func(i)]

                  return first,second


                  numbers = [1, 2, 3, 4]
                  even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)

                  print(even_numbers) # [2, 4]
                  print(odd_numbers) # [1, 3]





                  share|improve this answer
























                    up vote
                    2
                    down vote













                    I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:



                    def myFunc(iterable, func):

                    first = [i for i in iterable if func(i)]
                    second = [i for i in iterable if not func(i)]

                    return first,second


                    numbers = [1, 2, 3, 4]
                    even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)

                    print(even_numbers) # [2, 4]
                    print(odd_numbers) # [1, 3]





                    share|improve this answer






















                      up vote
                      2
                      down vote










                      up vote
                      2
                      down vote









                      I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:



                      def myFunc(iterable, func):

                      first = [i for i in iterable if func(i)]
                      second = [i for i in iterable if not func(i)]

                      return first,second


                      numbers = [1, 2, 3, 4]
                      even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)

                      print(even_numbers) # [2, 4]
                      print(odd_numbers) # [1, 3]





                      share|improve this answer












                      I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:



                      def myFunc(iterable, func):

                      first = [i for i in iterable if func(i)]
                      second = [i for i in iterable if not func(i)]

                      return first,second


                      numbers = [1, 2, 3, 4]
                      even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)

                      print(even_numbers) # [2, 4]
                      print(odd_numbers) # [1, 3]






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 8 at 9:27









                      Laurent H.

                      3,8261530




                      3,8261530




















                          up vote
                          2
                          down vote













                          Full code following @jonrsharpe suggestion.



                          import itertools

                          def fork(iterable):
                          "Returns list of even, odd elements of a list"
                          t1, t2 = itertools.tee(iterable)
                          pred = lambda i: i % 2 == 0
                          return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))

                          odd, even = fork([1,2,3,4,5])
                          print(odd)
                          print(even)


                          Alternative numpy version which might be faster for big arrays



                          import numpy as np

                          def fork(iterable):
                          "Returns array of even, odd elements of an array"
                          iterable_array = np.asarray(iterable)
                          mask = (iterable_array % 2 == 0)
                          return iterable_array[~mask], iterable_array[mask]





                          share|improve this answer


























                            up vote
                            2
                            down vote













                            Full code following @jonrsharpe suggestion.



                            import itertools

                            def fork(iterable):
                            "Returns list of even, odd elements of a list"
                            t1, t2 = itertools.tee(iterable)
                            pred = lambda i: i % 2 == 0
                            return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))

                            odd, even = fork([1,2,3,4,5])
                            print(odd)
                            print(even)


                            Alternative numpy version which might be faster for big arrays



                            import numpy as np

                            def fork(iterable):
                            "Returns array of even, odd elements of an array"
                            iterable_array = np.asarray(iterable)
                            mask = (iterable_array % 2 == 0)
                            return iterable_array[~mask], iterable_array[mask]





                            share|improve this answer
























                              up vote
                              2
                              down vote










                              up vote
                              2
                              down vote









                              Full code following @jonrsharpe suggestion.



                              import itertools

                              def fork(iterable):
                              "Returns list of even, odd elements of a list"
                              t1, t2 = itertools.tee(iterable)
                              pred = lambda i: i % 2 == 0
                              return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))

                              odd, even = fork([1,2,3,4,5])
                              print(odd)
                              print(even)


                              Alternative numpy version which might be faster for big arrays



                              import numpy as np

                              def fork(iterable):
                              "Returns array of even, odd elements of an array"
                              iterable_array = np.asarray(iterable)
                              mask = (iterable_array % 2 == 0)
                              return iterable_array[~mask], iterable_array[mask]





                              share|improve this answer














                              Full code following @jonrsharpe suggestion.



                              import itertools

                              def fork(iterable):
                              "Returns list of even, odd elements of a list"
                              t1, t2 = itertools.tee(iterable)
                              pred = lambda i: i % 2 == 0
                              return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))

                              odd, even = fork([1,2,3,4,5])
                              print(odd)
                              print(even)


                              Alternative numpy version which might be faster for big arrays



                              import numpy as np

                              def fork(iterable):
                              "Returns array of even, odd elements of an array"
                              iterable_array = np.asarray(iterable)
                              mask = (iterable_array % 2 == 0)
                              return iterable_array[~mask], iterable_array[mask]






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Aug 8 at 9:32

























                              answered Aug 8 at 9:19









                              user2653663

                              875713




                              875713




















                                  up vote
                                  2
                                  down vote













                                  The simplest possible implementation would be probably



                                  def partition(xs, cond):
                                  res = ,
                                  for x in xs:
                                  res[not cond(x)].append(x)
                                  return res





                                  share|improve this answer




















                                  • Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
                                    – roganjosh
                                    Aug 8 at 10:17











                                  • @roganjosh: sure, that's easy to optimize if needed
                                    – georg
                                    Aug 8 at 10:19














                                  up vote
                                  2
                                  down vote













                                  The simplest possible implementation would be probably



                                  def partition(xs, cond):
                                  res = ,
                                  for x in xs:
                                  res[not cond(x)].append(x)
                                  return res





                                  share|improve this answer




















                                  • Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
                                    – roganjosh
                                    Aug 8 at 10:17











                                  • @roganjosh: sure, that's easy to optimize if needed
                                    – georg
                                    Aug 8 at 10:19












                                  up vote
                                  2
                                  down vote










                                  up vote
                                  2
                                  down vote









                                  The simplest possible implementation would be probably



                                  def partition(xs, cond):
                                  res = ,
                                  for x in xs:
                                  res[not cond(x)].append(x)
                                  return res





                                  share|improve this answer












                                  The simplest possible implementation would be probably



                                  def partition(xs, cond):
                                  res = ,
                                  for x in xs:
                                  res[not cond(x)].append(x)
                                  return res






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Aug 8 at 10:13









                                  georg

                                  139k30189286




                                  139k30189286











                                  • Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
                                    – roganjosh
                                    Aug 8 at 10:17











                                  • @roganjosh: sure, that's easy to optimize if needed
                                    – georg
                                    Aug 8 at 10:19
















                                  • Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
                                    – roganjosh
                                    Aug 8 at 10:17











                                  • @roganjosh: sure, that's easy to optimize if needed
                                    – georg
                                    Aug 8 at 10:19















                                  Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
                                  – roganjosh
                                  Aug 8 at 10:17





                                  Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
                                  – roganjosh
                                  Aug 8 at 10:17













                                  @roganjosh: sure, that's easy to optimize if needed
                                  – georg
                                  Aug 8 at 10:19




                                  @roganjosh: sure, that's easy to optimize if needed
                                  – georg
                                  Aug 8 at 10:19










                                  up vote
                                  0
                                  down vote













                                  You can create your own function:



                                  l = [1, 2, 3, 4]
                                  def fork(l,key):
                                  return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
                                  even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
                                  print(even_numbers)
                                  print(odd_numbers)


                                  Output:



                                  [2, 4]
                                  [1, 3]





                                  share|improve this answer
























                                    up vote
                                    0
                                    down vote













                                    You can create your own function:



                                    l = [1, 2, 3, 4]
                                    def fork(l,key):
                                    return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
                                    even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
                                    print(even_numbers)
                                    print(odd_numbers)


                                    Output:



                                    [2, 4]
                                    [1, 3]





                                    share|improve this answer






















                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      You can create your own function:



                                      l = [1, 2, 3, 4]
                                      def fork(l,key):
                                      return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
                                      even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
                                      print(even_numbers)
                                      print(odd_numbers)


                                      Output:



                                      [2, 4]
                                      [1, 3]





                                      share|improve this answer












                                      You can create your own function:



                                      l = [1, 2, 3, 4]
                                      def fork(l,key):
                                      return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
                                      even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
                                      print(even_numbers)
                                      print(odd_numbers)


                                      Output:



                                      [2, 4]
                                      [1, 3]






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Aug 8 at 9:23









                                      U9-Forward

                                      5,7532428




                                      5,7532428












                                          Popular posts from this blog

                                          Which professions warranted travel in Medieval times?

                                          How do so many people here on Academia.SE, and in general, afford lavish higher education programs?

                                          Trouble downloading packages list due to a “Hash sum mismatch” error