Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python idiomatic python for loop if else statement

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]

like image 974
ragesz Avatar asked Nov 12 '15 18:11

ragesz


1 Answers

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)] 
like image 90
Morgan Thrapp Avatar answered Sep 17 '22 20:09

Morgan Thrapp