Find Elements in One Python List but Not Another

Return a new list containing only the elements from list A that are not present in list B, preserving duplicates and order.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

12 lines
Python 3.9+
def difference_elements(a, b):
    """Return elements present in list a but not in list b."""
    set_b = set(b)
    return [item for item in a if item not in set_b]

if __name__ == "__main__":
    a = [1, 2, 3, 4, 5, 3, 2]
    b = [2, 4, 6]
    result = difference_elements(a, b)
    print(f"A: {a}")
    print(f"B: {b}")
    print(f"Elements in A not in B: {result}")

Output

stdout
A: [1, 2, 3, 4, 5, 3, 2]
B: [2, 4, 6]
Elements in A not in B: [1, 3, 5, 3]

How it works

This code builds a set from list B to provide O(1) membership tests, then uses a list comprehension to iterate over A and keep items not found in the set. Using a set for B is crucial for performance; checking item not in set_b is constant-time on average, whereas item not in b would be O(n) per check. The list comprehension preserves the original order of A and includes duplicate elements from A that are not in B. If duplicates in A are not needed, convert the result to a set or use set operations.

Common mistakes

  • Using `item not in b` inside the comprehension (O(n) lookup per item) instead of building a set first.
  • Expecting set-like behavior and forgetting duplicate elements from A are preserved.
  • Confusing this with the symmetric difference, which returns elements in either list but not both.

Variations

  1. Use `list(set(a) - set(b))` for a set difference that removes duplicates and ignores element order.
  2. Use `[x for x in a if x not in set_b]` with a prebuilt set for readability.

Real-world use cases

  • Filtering out items already processed by an ID list before batching API calls.
  • Removing blacklisted usernames from a user list during a cleanup job.
  • Computing which products from an inventory feed are missing from a database lookup table.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.