This rule raises an issue when code checks if an element exists in a set using the in operator before calling remove() on
that element.
Checking whether an element exists in a set before removing it is unnecessary:
if x in my_set:
my_set.remove(x)
This pattern has two problems:
in) and another for the
removal (remove()). Each lookup has a cost.discard() method specifically for this use case. Using it makes the code more
Pythonic and signals intent more clearly.The discard() method combines both operations into a single call. It removes the element if it exists and does nothing otherwise:
my_set.discard(x) # Single lookup, no exception if x is not present
Using discard() improves readability and removes a redundant hash table lookup. In loops or performance-critical code, eliminating
these extra lookups can provide measurable improvements.
Replace the conditional check and remove() call with a single discard() call. The discard() method safely
removes the element if it exists and does nothing if it does not, without raising an exception.
my_set = {1, 2, 3, 4, 5}
value = 3
if value in my_set: # Noncompliant
my_set.remove(value)
my_set = {1, 2, 3, 4, 5}
value = 3
my_set.discard(value)
set.discard() methodset.remove() method