Skip to content

Del Comprehension

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: del-comprehension

Section titled “Sourcery refactoring id: del-comprehension”

Replaces cases where deletions are made via for loops with comprehensions

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]
x1 = {"a": 1, "b": 2, "c": 3}
x1 = {key: value for key, value in x1.items() if key in x0}

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.