[PR #1392] Add ruff rule PERF for performance #2002

Closed
opened 2026-01-29 20:56:52 +00:00 by claunia · 0 comments
Owner

Original Pull Request: https://github.com/google/brotli/pull/1392

State: closed
Merged: Yes


% 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)
**Original Pull Request:** https://github.com/google/brotli/pull/1392 **State:** closed **Merged:** Yes --- % `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 ```python original = list(range(10000)) filtered = [] for i in original: if i % 2: filtered.append(i) ``` Use instead: ```python 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: ```python original = list(range(10000)) filtered.extend(x for x in original if x % 2) ```
claunia added the pull-request label 2026-01-29 20:56:52 +00:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/brotli#2002