How can I use the else in the Python for idiomatic loop? Without else I can write, for example:
res = [i for i in [1,2,3,4,5] if i < 4]
Result: [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] normal code for this is:
res = [] for i in [1,2,3,4,5]: if i < 4: res.append(i) else: res.append(0)
Result: [1, 2, 3, 0, 0]
python for-loop if-statement idiomatic
ragesz
source share