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.

Why is this an issue?

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:

  1. double lookup: the code performs two hash table lookups - one for the membership check (in) and another for the removal (remove()). Each lookup has a cost.
  2. less idiomatic: Python provides the 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

What is the potential impact?

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.

How to fix it

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.

Code examples

Noncompliant code example

my_set = {1, 2, 3, 4, 5}
value = 3

if value in my_set:  # Noncompliant
    my_set.remove(value)

Compliant solution

my_set = {1, 2, 3, 4, 5}
value = 3

my_set.discard(value)

Resources

Documentation