That’s because you can’t use an else
condition there (e.g. you can’t append a zero to the list with that syntax).
In which case, I suppose if it works, then it works, though I would probably add some parenthesis to make it clearer what you’re trying to do.
totals = [(a/b) if b else 0 for a,b in zip(net,eff)]
The difference is what the if..else
statement is doing. In the first one, the comprehension looks at b, if it is not 0 it appends the result of (a/b), if it is 0 then it moves on to the next iteration. In the second one, the comprehension looks at b if it is not 0 it appends the result of (a/b), if it is 0 then it appends 0.
Throw this in script console to see the difference.
totals = [a/b for a,b in zip(net,eff) if b]
print totals
totals = []
for a,b in zip(net,eff):
if b:
totals.append(a/b)
print totals
totals = [(a/b) if b else 0 for a,b in zip(net,eff)]
print totals
totals = []
for a,b in zip(net,eff):
if b:
totals.append(a/b)
else:
totals.append(0)