Search code examples
pythonlist-comprehensiongenerator-expression

Why can I not have `else` (from if / else) with python generator expressions?


I have the following code, which works fine:

incl_list = ['A']
my_list = [{'A': 1, 'B': 'world'}, {'A': 4, 'B': 'hello'}]
result = '\n'.join(','.join(f'{key}={value}' for key, value in record.items() if key in incl_list) for record in my_list)

The result yields:

'A=1\nA=4'

My question is why can I not add an else statement, like so:

result = '\n'.join(','.join(f'{key}={value}' for key, value in record.items() if key in incl_list) else 'ignore' for record in my_list)

similar to list-comprehension?

The error I get is:

 File "<ipython-input-276-201c8f88ac13>", line 1
    result = '\n'.join(','.join(f'{key}={value}' for key, value in record.items() if key in incl_list else 'ignore') for record in my_list)
                                                                                                         ^
SyntaxError: invalid syntax

Solution

  • Your else statement needs to go together with an if statement, when using inside a comprehension, thus you could modify your code like so to make it work

    result = '\n'.join(','.join(f'{key}={value}' if key in incl_list else 'ignore' for key, value in record.items()) for record in my_list)