python list comprehension with multiple 'if's

Stefan picture Stefan · Mar 6, 2013 · Viewed 59.1k times · Source

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?

Answer

Emil Vikström picture Emil Vikström · Mar 6, 2013

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.