snipt

Ctrl+h for KB shortcuts

Python

Partition a Python list in two sublists according to a Boolean condition (eager version)

def split_on_condition(seq, condition):
    
    a, b = [], []
    
    for item in seq:
        (a if condition(item) else b).append(item)
    # end for
    
    return a,b

# end def split_on_condition
https://snipt.net/embed/8ec8bfd8ed8be0fc7cd17ee2b6ca9fc4/
/raw/8ec8bfd8ed8be0fc7cd17ee2b6ca9fc4/
8ec8bfd8ed8be0fc7cd17ee2b6ca9fc4
python
Python
11
2019-07-16T03:55:38
True
False
False
Apr 22, 2013 at 05:49 AM
/api/public/snipt/59705/
partition-a-python-list-in-two-sublists-according-to-a-boolean-condition-eager-version
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1"> 1</a> <a href="#L-2"> 2</a> <a href="#L-3"> 3</a> <a href="#L-4"> 4</a> <a href="#L-5"> 5</a> <a href="#L-6"> 6</a> <a href="#L-7"> 7</a> <a href="#L-8"> 8</a> <a href="#L-9"> 9</a> <a href="#L-10">10</a> <a href="#L-11">11</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a><span class="k">def</span> <span class="nf">split_on_condition</span><span class="p">(</span><span class="n">seq</span><span class="p">,</span> <span class="n">condition</span><span class="p">):</span> </span><span id="L-2"><a name="L-2"></a> </span><span id="L-3"><a name="L-3"></a> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="p">[],</span> <span class="p">[]</span> </span><span id="L-4"><a name="L-4"></a> </span><span id="L-5"><a name="L-5"></a> <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">seq</span><span class="p">:</span> </span><span id="L-6"><a name="L-6"></a> <span class="p">(</span><span class="n">a</span> <span class="k">if</span> <span class="n">condition</span><span class="p">(</span><span class="n">item</span><span class="p">)</span> <span class="k">else</span> <span class="n">b</span><span class="p">)</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">item</span><span class="p">)</span> </span><span id="L-7"><a name="L-7"></a> <span class="c1"># end for</span> </span><span id="L-8"><a name="L-8"></a> </span><span id="L-9"><a name="L-9"></a> <span class="k">return</span> <span class="n">a</span><span class="p">,</span><span class="n">b</span> </span><span id="L-10"><a name="L-10"></a> </span><span id="L-11"><a name="L-11"></a><span class="c1"># end def split_on_condition</span> </span></pre></div> </td></tr></table>
Python