Search code examples
pythonif-statementlist-comprehensiongenerator-expression

How to put if/else statements in list comprehension along with multiple supporting expressions


How can i convert this kind of loops into list comprehension.

for x in email_data:
    data = Apply_Filters(x[0])
    if len(data.split()) > 1:
        email_data2.append(tuple([x[1], data]))

So far my search got me to the comprehensions with only if else statements without performing any other functions like .

[y if y not in b else other_value for y in a]

But i first have to apply a function to a looping variable and then have to use conditional structure.

Any help would be appreciated.


Solution

  • Something like this might work:

    [(x_1, data) for x_1, data in map(lambda x: (x[1], Apply_Filters(x[0])), email_data) if len(data.split()) > 1]
    

    Trying to save rows such way is a terrible idea IMO.