How does this reduce + lambda list filter function work?
<p>I saw the following code to filter a list into two classes:</p>

<pre><code>reduce(lambda(a,b),c: (a+[c],b) if c &gt; 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))
</code></pre>

<p>How does it work? the <code>([], [])</code> looks initializing the <code>(a, b)</code> in lambda, but how does it work step by step?</p>

<p>This also doesn't seem to be working in Python 3. Why is that? </p>

<p>Take a look at the following experiment:</p>

<pre><code>&gt;&gt;&gt; reduce(lambda(a,b),c: (a+[c],b) if c &gt; 60 else (a,b + [c]), [49],([],[]))
([], [49])
&gt;&gt;&gt; reduce(lambda(a,b),c: (a+[c],b) if c &gt; 60 else (a,b + [c]), [49,58],([],[]))
([], [49, 58])
&gt;&gt;&gt; reduce(lambda(a,b),c: (a+[c],b) if c &gt; 60 else (a,b + [c]), [49,58,76],([],[]))
([76], [49, 58])
&gt;&gt;&gt; reduce(lambda(a,b),c: (a+[c],b) if c &gt; 60 else (a,b + [c]), [49,58,76,82],([],[]))
([76, 82], [49, 58])
&gt;&gt;&gt; reduce(lambda(a,b),c: (a+[c],b) if c &gt; 60 else (a,b + [c]), [49,58,76,82,88,90],([],[]))
([76, 82, 88, 90], [49, 58])
</code></pre>

<p>Function <code>reduce</code> is described as follows:</p>

<pre><code>reduce(...)
    reduce(function, sequence[, initial]) -&gt; value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
</code></pre>

<p>In our example, function is a lambda function with first argument as a 2-element tuple <code>(a,b)</code> and second argument as an integer <code>c</code> picked up from the list for processing. Since function produces a 2-element tuple of lists, it is initialized as <code>([], [])</code>. When processing starts, if the element is > 60, it is added to the first list of the tuple; else it is added to the second list of the tuple.</p>

<p>The syntax <code>a+[c]</code> is really the <code>extend</code> syntax of a list. We cannot do <code>a+c</code> since <code>a</code> is a list and <code>c</code> is an integer. Likewise, for <code>b+[c]</code></p>

python lambda reduce