OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

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

  • Thread starter Thread starter Parand
  • Start date Start date
P

Parand

Guest
I have some code like:

Code:
good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]

The goal is to split up the contents of mylist into two other lists, based on whether or not they meet a condition.

How can I do this more elegantly? Can I avoid doing two separate iterations over mylist? Can I improve performance by doing so?
<p>I have some code like:</p>
<pre><code>good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
</code></pre>
<p>The goal is to split up the contents of <code>mylist</code> into two other lists, based on whether or not they meet a condition.</p>
<p>How can I do this more elegantly? Can I avoid doing two separate iterations over <code>mylist</code>? Can I improve performance by doing so?</p>
 
Top