Documentation
As noted in the documentation for list comprehensions (and also in the reference docs on expressions, but not in the glossary which refers to an "if clause" in the singular), list/set/dict comprehensions can accept zero or more if clauses like so:
[i for i in range(10) if i % 2 if i % 3]
Looking at the bytecode generated with python -m dis, this appears to be strictly equivalent to:
[i for i in range(10) if i % 2 and i % 3]
(The last if was replaced by and)
It would be nice if this was documented, and ideally with examples.
I'm also personally curious why that feature exists so if someone could point me to an explanation I'd appreciate it. I didn't find anything in what I believe is the original PEP for list comprehensions (PEP 202).
Linked PRs
Documentation
As noted in the documentation for list comprehensions (and also in the reference docs on expressions, but not in the glossary which refers to an "if clause" in the singular), list/set/dict comprehensions can accept zero or more
ifclauses like so:Looking at the bytecode generated with
python -m dis, this appears to be strictly equivalent to:(The last
ifwas replaced byand)It would be nice if this was documented, and ideally with examples.
I'm also personally curious why that feature exists so if someone could point me to an explanation I'd appreciate it. I didn't find anything in what I believe is the original PEP for list comprehensions (PEP 202).
Linked PRs
ifstatements example for list comprehensions #138217