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>

<blockquote>
  <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>
</blockquote>

<p>At each point, the reduce sees a left hand operand, <code>(a, b)</code>, which is a pair of lists (initially two empty lists), and an element <code>c</code>. It adds the list <code>[c]</code> to either <code>a</code> or <code>b</code>, depending on whether it's larger than 60, and returns the new pair of lists. Thus, it will eventually return the pair of the elements larger than 60, and less than 60, respectively.</p>

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

<p>In Python3 you can't anymore define a function explicitly taking a tuple - <a href="https://www.python.org/dev/peps/pep-3113/" rel="nofollow">tuple unpacking has been removed</a>. So</p>

<pre><code>def foo((a, b)):
    ...
</code></pre>

<p>is illegal in Python3. This is the problem here as well (except in the form of a lambda).</p>

python lambda reduce