Skip to content

Conversation

@cclauss
Copy link
Contributor

@cclauss cclauss commented Nov 20, 2025

% ruff check --extend-select=C4,C90,PERF,RET,SIM,W

% ruff rule PERF401

manual-list-comprehension (PERF401)

Derived from the Perflint linter.

Fix is sometimes available.

What it does

Checks for for loops that can be replaced by a list comprehension.

Why is this bad?

When creating a transformed list from an existing list using a for-loop,
prefer a list comprehension. List comprehensions are more readable and
more performant.

Using the below as an example, the list comprehension is ~10% faster on
Python 3.11, and ~25% faster on Python 3.10.

Note that, as with all perflint rules, this is only intended as a
micro-optimization, and will have a negligible impact on performance in
most cases.

Example

original = list(range(10000))
filtered = []
for i in original:
    if i % 2:
        filtered.append(i)

Use instead:

original = list(range(10000))
filtered = [x for x in original if x % 2]

If you're appending to an existing list, use the extend method instead:

original = list(range(10000))
filtered.extend(x for x in original if x % 2)

@eustas
Copy link
Collaborator

eustas commented Nov 20, 2025

Cool. Thanks.

@cclauss
Copy link
Contributor Author

cclauss commented Nov 23, 2025

Thanks for the review. Three required GitHub Actions workflows need maintainer approval below to run.

@eustas
Copy link
Collaborator

eustas commented Nov 24, 2025

No worries about workflows - landing of PR in google/brotli is a bit more complicated than just almost everywhere in GH. You might have noticed that it is "copybara-service" pushes commits...

@copybara-service copybara-service bot merged commit 5fa73e2 into google:master Nov 24, 2025
49 checks passed
@cclauss cclauss deleted the comprehensions branch November 24, 2025 11:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants