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”Description:
Section titled “Description:”Replaces cases where deletions are made via for loops with comprehensions
Before:
Section titled “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:
Section titled “After:”x1 = {"a": 1, "b": 2, "c": 3}x1 = {key: value for key, value in x1.items() if key in x0}Explanation:
Section titled “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.