Python if else statement not working in reduce lambda function
<p>I'm new to <code>lambda</code> and <code>reduce</code> in Python and I don't understand why this function doesn't work:</p>

<pre><code>def my_func(str):
    symbols = ['_', '-']
    return reduce(lambda x, y: ' ' + y if x in symbols else x + y, str)

my_func('foo_bar-baz')  # 'foo_bar-baz'
</code></pre>

<p>I expected the output to be <code>'foo bar baz'</code>.</p>

<p>Does anyone understand what's wrong here?</p>

<p>You seem to be confused about the order of the arguments to <code>reduce</code>'s function argument. The first argument is the running total, the second is the new data. In your example, <code>x</code> is the built-up string, <code>y</code> is the new character.</p>

<p>Try this:</p>

<pre><code>def my_func(str):
    symbols = ['_', '-']
    return reduce(lambda x, y: x + (' ' if y in symbols else y), str)

print my_func('foo_bar-baz')  # 'foo bar baz'
</code></pre>

<p>Note the bug in this: in the first call to the lambda expression, <code>x</code> is <code>str[0]</code>, and <code>y</code> is <code>str[1]</code>. Thus, if the first character in the passed-in string is a symbol, it is not translated. </p>

<pre><code>print my_func('-foo_bar-baz')
-foo bar baz
</code></pre>

<p>This can be solved by providing the third argument to <code>reduce()</code>:</p>

<pre><code>def my_func(str):
    symbols = ['_', '-']
    return reduce(lambda x, y: x + (' ' if y in symbols else y), str, '')

print my_func('foo_bar-baz')  # 'foo bar baz'
print my_func('-foo_bar-baz')  # ' foo bar baz'
</code></pre>

python lambda reduce