if-else sentence in one-line-python
<p>I have some code:</p>

<pre><code>a_part = [2001, 12000]
b_part = [1001, 2000]
c_part = [11, 1000]
d_part = [1, 10]
data = range(1, 12000)
labels = [a_part, b_part, c_part, d_part]
sizes = []

# ---

for part in labels:
    sum = 0
    for each in data:
        sum += each if each &gt;= part[0] and each &lt;= part[1] else 0
        # error
        # sum += each if each &gt;= part[0] and each &lt;= part[1] 
    sizes.append(sum)
print(sizes)
</code></pre>

<p>And I rewrote this to be more Pythonic:</p>

<pre><code>sizes = [sum(x for x in data if low&lt;=x&lt;=high) for low,high in labels]
# error
# sizes = [sum(x for x in data if low&lt;=x&lt;=high else 0) for low else 0,high in labels]
print(sizes)
</code></pre>

<p>I found that in the first snippet I can't leave out <code>else 0</code> while the second example can't contain <code>else 0</code>.</p>

<p>What is the difference <code>else 0</code> makes between these examples?</p>

<p>You have two very different things here.</p>

<p>In the first you have an expression, and are using a <a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="nofollow"><em>conditional expression</em></a> to produce the value; that requires an <code>else</code> because an expression always needs to produce <em>something</em>.</p>

<p>For example, if you wrote:</p>

<pre><code>sum += each if each &gt;= part[0] and each &lt;= part[1]  # removing "else 0"
</code></pre>

<p>then what would be added to the sum if the test was false?</p>

<p>In the second you have a <a href="https://docs.python.org/3/reference/expressions.html#generator-expressions" rel="nofollow"><em>generator expression</em></a>, and the <code>if</code> is part of the possible parts (called <a href="https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries" rel="nofollow"><code>comp_if</code> in the grammar</a>), next to (nested) <code>for</code> loops. Like an <code>if ...:</code> statement, it filters what elements in the sequence are used, and that doesn't need to produce a value in the <em>false</em> case; you would not be filtering otherwise.</p>

<p>To bring that back to your example:</p>

<pre><code>sum(x for x in data if low&lt;=x&lt;=high)
</code></pre>

<p>when the <code>if</code> test is false, that <code>x</code> is just omitted from the loop and not summed. You'd do the same thing in the first example with:</p>

<pre><code>if each &gt;= part[0] and each &lt;= part[1]:
    # only add to `sum` if true
    sum += each
</code></pre>

python