Python idiomatic python for if else statement loop

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]

+7
python for-loop if-statement idiomatic
source share
1 answer

You were close, you just need to move the three to the part of understanding the list where you create the value.

 res = [i if i < 4 else 0 for i in range(1,6)] 
+11
source share

All Articles