python / python/cpython

Document usage of comprehensions with multiple if clauses

Open
#137,818 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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
  • gh-138217

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing linked PR gh-138217, then compare the list-comprehension tutorial, expressions reference, and glossary sections named in the issue. Done means the documentation explains that comprehensions support multiple if clauses and includes a representative example, with the rationale added if the existing references support it.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.