Skip to content

Del comprehension

Sourcery refactoring id: del-comprehension

Description:

Replaces cases where deletions are made via for loops with comprehensions

Before:

x1 = {"a": 1, "b": 2, "c": 3}
for key in x1.copy():  # can't iterate over a variable that changes size
    if key not in x0:
        del x1[key]

After:

x1 = {"a": 1, "b": 2, "c": 3}
x1 = {key: value for key, value in x1.items() if key in x0}

Explanation:

When creating a filtered list in Python it is shorter and more readable to use a comprehension than to copy a list and delete the unneeded keys.

Back to top