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.
Python code
12 linesdef 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
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
- Use `list(set(a) - set(b))` for a set difference that removes duplicates and ignores element order.
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.