How can I use else
statement in an idiomatic Python for
loop? Without else
I can write e.g.:
res = [i for i in [1,2,3,4,5] if i < 4]
The result is: [1, 2, 3]
The normal form of the above code is:
res = []
for i in [1,2,3,4,5]:
if i < 4:
res.append(i)
The result is the same as in idiomatic form: [1, 2, 3]
And I want this:
res = [i for i in [1,2,3,4,5] if i < 4 else 0]
I get SyntaxError: invalid syntax
. The result should be: [1, 2, 3, 0, 0]
The normal code of this is:
res = []
for i in [1,2,3,4,5]:
if i < 4:
res.append(i)
else:
res.append(0)
The result is: [1, 2, 3, 0, 0]
You were close, you just have to move the ternary to the part of the list comprehension where you're creating the value.
res = [i if i < 4 else 0 for i in range(1,6)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With