Skip to content

Document usage of comprehensions with multiple if clauses #137818

@bmispelon

Description

@bmispelon

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions