Quantcast
Channel: How can I partition (split up, divide) a list based on a condition? - Stack Overflow
Viewing all articles
Browse latest Browse all 41

Answer by winden for How can I partition (split up, divide) a list based on a condition?

$
0
0

Problem with all proposed solutions is that it will scan and apply the filtering function twice. I'd make a simple small function like this:

def split_into_two_lists(lst, f):    a = []    b = []    for elem in lst:        if f(elem):            a.append(elem)        else:            b.append(elem)    return a, b

That way you are not processing anything twice and also are not repeating code.


Viewing all articles
Browse latest Browse all 41

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>