Is / else / if possible in a list comprehension?

I would like to know if it is possible to use a list comprehension with if

/ else

that does not have to contain a list of the same length as the length of the list being processed? (i.e. no final else

)

>>> L = [0, 1, 2, 3, 4, 5, 6]
>>> [v * 10 if v < 3 else v * 2 if v > 3 else v for v in L] #if/else/if/else
[0, 10, 20, 3, 8, 10, 12]

      

works great. But suppose I want to omit 3 to get:

[0, 10, 20, 8, 10, 12]  # No number 3

      

I would have thought this would work:

>>> [v * 10 if v < 3 else v * 2 if v > 3 for v in L] #if/else/if

      

But this is a syntax error.

So I thought that "maybe" it would work:

>>> [v * 10 if v < 3 else v * 2 if v > 3 else pass for v in L] #if/else/if/else pass

      

But this is not the case.

This is a matter of curiosity, I realize this is not necessarily the most readable / appropriate approach to the above processing.

Am I missing something? It can be done? (I'm on python 2.6.5)

+3


source to share


4 answers


Yes it is possible:

[foo for foo in bar if foo.something]

      

Or in your case:



[v * 10 if v < 3 else v * 2 for v in L if v != 3]

      

I have also mentioned in the docs .

+14


source


Put the filter condition after the loop:

 [v * 10 if v < 3 else v * 2 for v in L if v != 3]

      



returns

[0, 10, 20, 8, 10, 12]

      

+4


source


    A=[[x*2, x*10][x <3] for x in L if x!=3]

      

0


source


Wrong to do

out = []
for v in L:
    if v < 3:
        out.append(v * 10)
    elif v > 3:
        out.append(v * 2)
    else:
        pass

      

-2


source







All Articles