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>

<pre><code>x if y else z
</code></pre>

<p>This is an inline-if expression which returns a value. It must always return a value, it cannot not return a value, hence it must contain an <code>else</code> clause.</p>

<pre><code>[x for x in y if z]
</code></pre>

<p>This is a list comprehension. The <code>if</code> here acts as a filter for the loop. It's equivalent to <code>for x in y: if z: ...</code>.</p>

<p>To have an <code>else</code> in there, you put the inline-if expression in place of <code>x</code>:</p>

<pre><code>[x if y else z for foo in bar]
</code></pre>

python