Back to Python
2026-01-035 min read

difference() (Python Programming)

Learn difference() (Python Programming) step by step with clear examples and exercises.

Why This Matters

In this comprehensive lesson on Python programming, we will delve into the world of Set operations and explore the difference() method, an essential tool for finding the unique elements in a set. Mastering this skill is crucial for coding interviews, debugging real-world issues, and understanding the intricacies of Python programming. Let's embark on our journey!

Prerequisites

To fully grasp this lesson, you should have a solid understanding of the following concepts:

  1. Python variables and data types
  2. Python lists and tuples
  3. Basic Python syntax and control structures (if-else statements, loops)
  4. Understanding what sets are in Python and how to create them
  5. Familiarity with common Python functions such as len(), in, and isinstance()
  6. Knowledge of Set operations like union(), intersection(), and symmetric_difference()

Core Concept

A Set in Python is a collection of unique elements that cannot be ordered or indexed. The difference() method computes the difference between two sets by returning a new set containing only the elements present in the first set but not in the second one. Let's see this in action:

Creating two sets

set1 = {1, 3, 5, 7, 9}

set2 = {2, 3, 5, 7, 11}

Using the difference() method to find elements unique to set1

result = set1.difference(set2)

print(result) # Output: {1, 9}

In the example above, we created two sets `set1` and `set2`. The `difference()` method was used to compute the difference between these two sets, resulting in a new set containing only the elements present in `set1` but not in `set2`.

### Internals (memory/CPU)
The `difference()` method works by iterating through each element in the first set and checking if it exists in the second set. If an element is found in both sets, it is skipped over. The resulting set contains only the elements that were not found in the second set. This operation has a linear time complexity of O(m + n), where m and n are the number of elements in the first and second set, respectively.

Worked Example

Let's consider a practical example where we need to find the unique students who have enrolled for either Mathematics or Physics but not both:

Students enrolled for Mathematics and/or Physics

math_students = {"Alice", "Bob", "Charlie", "David", "Eve"}

physics_students = {"Alice", "Bob", "Carol", "Dave", "Eve", "Frank"}

Finding students who have enrolled for either Mathematics or Physics but not both

unique_students = math_students.union(physics_students) # Combine both sets

unique_students = unique_students - (math_students & physics_students) # Find the difference between students enrolled in both subjects

print(unique_students) # Output: {Carol, Frank}

In this example, we first combined the two sets using the `union()` method. Then, we found the intersection of these two sets to identify the students who were enrolled in both Mathematics and Physics. Finally, we used set subtraction (`-`) to find the unique students who were either enrolled for Mathematics or Physics but not both.

Common Mistakes

  1. Forgetting parentheses: When working with multiple sets, proper use of parentheses is crucial to ensure correct operation order. For example: set1.difference(set2 & set3) should be written as set1.difference(set2 and set3).
  1. Not checking the result: Always check the result of the difference() method to make sure it contains the expected elements and is free of any unexpected values.
  1. Using mutable sets in a set operation: If you use a mutable set (like list or dictionary) as an argument for set operations, the original set will be modified. To avoid this, convert the mutable set to a frozen set using frozenset() before performing the operation:

Creating a mutable set

my_set = set([1, 2, 3])

Converting the mutable set to a frozen set before performing the operation

result = my_set.difference(frozenset([4, 5]))


### Common Mistakes (Cont'd)
4. **Ignoring duplicate elements**: When comparing sets with duplicate elements, keep in mind that the `difference()` method will only consider each unique element once. This means that if both sets contain duplicates, the result may not be what you expect.

5. **Not considering empty sets**: The `difference()` method returns an empty set when one of the input sets is empty or when both sets are identical but have different orders.

Practice Questions

  1. Given two sets set1 = {1, 2, 3, 4} and set2 = {4, 5, 6}, find the difference between these two sets using the difference() method.
  1. Write a Python script to find the unique employees who have either worked in the Sales or Marketing department but not both. Assume we have two sets sales_employees = {"Alice", "Bob", "Charlie", "David", "Eve"} and marketing_employees = {"Carol", "Dave", "Eve", "Frank", "Grace"}.
  1. Given three sets set1 = {1, 2, 3}, set2 = {4, 5, 6} and set3 = {7, 8, 9}, find the difference between these three sets using the difference() method.

FAQ

  1. What happens if one or both sets are empty when using the difference() method?

When either set is empty, an empty set (set()) will be returned. If both sets are empty, no error will occur, and an empty set will still be returned.

  1. Can I use the difference() method with multiple sets at once?

Yes, you can find the intersection of a set with multiple other sets using the symmetric_difference() method or by calling difference() for each set separately. However, keep in mind that this may not always give the expected result if the sets have common elements.

  1. What is the time complexity of the difference() method in Python?

The time complexity of the difference() method is O(m + n), where m and n are the number of elements in the first and second set, respectively. This means that the method has a linear time complexity.

  1. What happens if I use a mutable set as an argument for the difference() method?

If you use a mutable set (like list or dictionary) as an argument for the difference() method, it will raise a TypeError since sets cannot contain mutable objects. To avoid this, convert the mutable set to a frozen set using frozenset() before performing the operation:

Creating a mutable set

my_set = set([1, 2, 3])

Converting the mutable set to a frozen set before performing the operation

result = my_set.difference(frozenset([4, 5]))


5. **Can I use the difference() method to find the common elements between two sets?**
No, the `difference()` method is used to find the unique elements in a set that are not present in another set. To find the common elements between two sets, you should use the `intersection()` method instead:

Two sets with common elements

set1 = {1, 2, 3}

set2 = {2, 4, 6}

Finding the common elements using intersection()

common_elements = set1.intersection(set2)

print(common_elements) # Output: {2}

difference() (Python Programming) | Python | XQA Learn