Inefficient membership test (ARCH2075)
Ce contenu n’est pas encore disponible dans votre langue.
Key python.performance.inefficient-membership-test · Severity info · Category performance
An in check against a list is O(n) and slow when repeated, especially inside a loop. Convert the searched collection to a set for O(1) lookups.
Incorrect
Section titled “Incorrect”def filter_allowed(items): allowed = ["read", "write", "admin", "audit"] return [i for i in items if i.role in allowed]Correct
Section titled “Correct”def filter_allowed(items): allowed = {"read", "write", "admin", "audit"} return [i for i in items if i.role in allowed]Define the repeatedly-tested collection as a set instead of a list.