Set Operations in Python

Master Python set operations: union, intersection, difference, and symmetric difference. Use both operators and methods to compare and combine sets efficiently.

5 min read

Set operations are the feature that elevates sets from a simple container of unique items to a data-processing tool that can answer questions about relationships between collections. With four operators and their corresponding methods, you can combine sets, find their overlap, identify what is unique to each, and compute the elements that appear in one but not the other. These operations mirror the mathematical concepts of union, intersection, difference, and symmetric difference, and because sets use a hash table internally, each operation stays fast even on large sets.

If you have read about working with Python sets and adding and removing set items, you already know how to create and populate sets. The operations covered in this article produce new sets rather than modifying the originals. Each operation has both an operator form, written with a symbol between two set operands, and a method form, written as a method call that accepts any iterable as its argument. The operator forms are more concise and readable when both sides are already sets. The method forms are more flexible because they accept lists, tuples, strings, and any other iterable without requiring an explicit conversion to a set first.

Union: combining sets

The union of two sets is a new set containing every element that appears in either of the originals. Duplicates are naturally eliminated because the result is itself a set. The pipe operator between two sets computes the union, and the union method computes the same result while accepting any iterable as its argument.

pythonpython
a = {1, 2, 3}
b = {3, 4, 5}
combined = a | b

The result is the set containing 1, 2, 3, 4, and 5. The element 3 appears in both a and b but only once in the union. The method form produces the same result, and calling the union method directly with a list like [3, 4, 5] works without requiring an explicit conversion to a set first. This flexibility makes the method form the better choice when your second collection is not already a set.

Union is the set operation you will use most often in everyday code. Any time you need to combine two sources of unique identifiers, merge allowlists, or collect all distinct values from multiple data sources, union gives you the answer in a single expression.

Intersection: finding common elements

The intersection of two sets is a new set containing only the elements that appear in both originals. The ampersand operator computes the intersection, and the intersection method accepts any iterable.

pythonpython
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
common = a & b

The result contains 3 and 4, the elements shared by both sets. Intersection answers questions like "which users belong to both groups," "which products appear in both catalogs," and "which tags are common to both articles." It is the natural tool for finding overlap between any two collections of unique identifiers.

The intersection method can accept multiple iterables when you need to find elements common to three or more collections. Passing several arguments returns elements that appear in all the collections simultaneously.

Difference: what is unique to one side

The difference of two sets is a new set containing elements that appear in the first set but not in the second. The minus operator computes the difference, and the difference method accepts any iterable. Unlike union and intersection, difference is not commutative: the order of the operands matters.

pythonpython
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
only_in_a = a - b

The result contains 1 and 2, the elements present in a but absent from b. Reversing the operands gives 5 and 6, the elements in b but absent from a. Difference answers questions like "which items are in the allowlist but not yet processed," "which users have not completed registration," and "which files exist in the source directory but not in the backup."

The difference method, like intersection, can accept multiple arguments. Passing extra arguments returns elements in the first set that are absent from all the others. Each additional argument filters out more elements from the result.

Symmetric difference: exclusive to each side

The symmetric difference of two sets is a new set containing elements that appear in either set but not in both. The caret operator computes the symmetric difference, and the symmetric_difference method accepts any iterable. Unlike regular difference, symmetric difference is commutative: the order of operands does not change the result.

pythonpython
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
exclusive = a ^ b

The result contains 1, 2, 5, and 6, the elements that are unique to each set. Symmetric difference answers questions like "which items differ between these two collections" and "what changed between yesterday's snapshot and today's." It is the set operation for finding what is different rather than what is common or what is missing.

The symmetric difference method accepts only one argument, not multiple. If you need the symmetric difference of three or more sets, you must chain calls or use a loop.

In-place operations with update variants

Every set operation has an in-place variant that modifies the original set instead of creating a new one. These methods end with the suffix _update and follow the same naming pattern as the read-only operations. The intersection_update method keeps only the common elements in the original set. The difference_update method removes elements found in the argument from the original set. The symmetric_difference_update method replaces the original with its symmetric difference with the argument.

The operator forms also support in-place modification using the augmented assignment operators. Writing the pipe-equals operator updates a set with the union of itself and another, the ampersand-equals updates with the intersection, and so on. These augmented assignment forms are concise and read naturally to anyone familiar with arithmetic assignment operators like += and -=.

For further exploration of how sets compare to other collection types in real-world scenarios, the article on choosing the right Python collection type provides decision-making guidance across all four built-in collection types.

With sets covered, the next collection type in this section is the dictionary. The article on working with Python dictionaries explains how dictionaries map keys to values for fast lookups.

Rune AI

Rune AI

Key Insights

  • Union (| or union()) combines all elements from both sets into a new set.
  • Intersection (& or intersection()) keeps only elements present in both sets.
  • Difference (- or difference()) keeps elements in the first set but not in the second.
  • Symmetric difference (^ or symmetric_difference()) keeps elements in either set but not both.
  • Operator forms require both operands to be sets; method forms accept any iterable.
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between the pipe operator and the union() method?

Both compute the union of two sets, returning a new set with all elements from both. The pipe operator (|) requires both operands to be sets. The union() method accepts any iterable as its argument, so you can pass a list, tuple, or string directly without converting it to a set first.

How do I find common elements between two sets?

Use the intersection operator (&) or the intersection() method. Both return a new set containing only the elements that appear in both sets. Like union(), the operator form requires both operands to be sets, while the method form accepts any iterable.

Does set difference care about order?

Yes. The expression A - B returns elements that are in A but not in B. The order matters because set difference is not commutative: A - B is different from B - A unless both sets contain the same elements. The symmetric difference (^) returns elements in either set but not in both, and it is commutative.

Conclusion

Set operations transform two collections into a single answer in one line of code. Union combines, intersection finds common ground, difference subtracts, and symmetric difference finds what is unique to each side. These four operations, available as both operators and methods, are the reason sets are indispensable for data comparison tasks.