Search code examples
pythonif-statementlist-comprehension

python list comprehension with multiple 'if's


We all know python's

[f(x) for x in y if g(x)]

syntax.

However the AST representation of list comprehension has room for more than one 'if' expression:

comprehension = (expr target, expr iter, expr* ifs)

Can somebody give me an example of python code that would produce an AST with more than one 'if' expression?


Solution

  • Just stack them after one another:

    [i for i in range(100) if i > 10 if i < 50]
    

    Produces the integers between 11 and 49, inclusive.