Sets and Set Operations
Learn how to store unique values, test membership, remove duplicates, and perform union, intersection, difference, and symmetric difference.
In this lesson, you will learn
- ✓Explain how sets store unique elements and why they are unordered.
- ✓Create non-empty and empty sets and remove duplicates from a sequence.
- ✓Use membership operators to check whether a value belongs to a set.
- ✓Calculate union, intersection, difference, and symmetric difference.
- ✓Modify sets safely using add(), remove(), and discard().
- ✓Trace set operations and identify common errors and edge cases.
1. Creating sets and understanding uniqueness
A set is a collection of distinct, hashable elements. If the same value appears multiple times when a set is created, the set stores only one occurrence of that value.
You can create a non-empty set using curly braces, such as numbers = {1, 2, 3}. You can also create a set from an iterable using set(), which is useful for removing duplicates from a list or a string.
To create an empty set, use set(). Empty curly braces, {}, create an empty dictionary instead of a set.
Sets are unordered. They do not preserve insertion order as a guaranteed positional order, so you should not depend on the order in which their elements are displayed or iterated over.
Set elements must be hashable. Integers and strings can be elements, but a list cannot be added directly because lists are mutable and unhashable.
Duplicate values are stored only once
The set literal contains repeated values, but a set stores each distinct value only once. sorted(numbers) creates a sorted list, making the displayed order predictable. len(numbers) returns 3 because the set contains three distinct elements.
Note
2. Membership and basic set operations
Use the in operator to test whether a value is present in a set. It returns True when the value is found and False otherwise. Use not in to test whether a value is absent.
The len() function returns the number of distinct elements in a set.
Sets do not support indexing or slicing. For example, numbers[0] raises TypeError because sets do not have positions like lists and tuples. If you need ordered access, convert the set into a sorted list or another suitable sequence.
Membership testing
The set contains the strings 'tea' and 'water'. The expression 'tea' in available returns True. The expression 'coffee' in available returns False because that value is absent. The expression 'coffee' not in available returns True.
Caution
3. Union: combining two sets
Union combines the elements from two sets. The result contains every distinct element that appears in either set or in both sets.
Use the | operator or the union() method. Neither operation modifies the original sets; each returns a new set.
If both sets contain the same value, the union includes that value only once.
Union using the | operator
Set a contains 1, 2, and 3. Set b contains 3 and 4. The union combines all distinct values from both sets. The shared value 3 appears only once, producing [1, 2, 3, 4] after sorting.
Note
4. Intersection: finding common elements
Intersection returns only the elements that occur in both sets.
Use the & operator or the intersection() method. The result may be empty if the sets have no common elements.
Intersection is useful when comparing groups, such as finding students enrolled in two courses or products that appear in two inventories.
Intersection using the & operator
The value 3 appears in both a and b. The values 1 and 2 appear only in a, while 4 appears only in b. The intersection contains only 3.
Note
5. Difference and symmetric difference
Difference returns the elements that belong to the left-hand set but not to the right-hand set. Use the - operator or difference() method.
Difference is directional. A - b and b - a can produce different results because each operation starts with a different set.
Symmetric difference returns elements that belong to either set but not to both. Use the ^ operator or symmetric_difference() method.
Union includes all distinct elements from both sets. Intersection includes shared elements. Difference includes elements unique to the left-hand set, while symmetric difference includes elements unique to either side.
Difference using the - operator
a - b contains elements in a that are not in b, so it contains 1 and 2. b - a contains elements in b that are not in a, so it contains 4. The shared value 3 is excluded from both differences.
Note
6. Modifying sets and handling edge cases
A regular Python set is mutable, so you can add or remove elements after creating it.
Use add(value) to add one element. If that value is already present, the set remains unchanged.
Use remove(value) to delete an existing element. If the value is absent, remove() raises KeyError. Use discard(value) when you want to remove an element only if it exists; discard() does not raise an error when the value is missing.
Use update(iterable) to add multiple elements from an iterable to an existing set. In contrast to union(), update() modifies the original set.
Set elements must be hashable. Attempting to add a list, for example, raises TypeError. If you need to represent a collection as one set element, a tuple of hashable values may be suitable.
Add an element
add(3) inserts 3 into the set. add(2) has no effect because 2 is already present. The resulting set contains three distinct elements.
Caution
7. Step-by-step dry run
To understand set operations, track which values belong to each set before and after each statement. The example below combines membership testing, intersection, and union.
Because sets are unordered, the example uses sorted() before printing the results. This makes the output deterministic and easier to compare.
Trace set operations in order
First, a contains 1, 2, and 3, while b contains 3 and 4. The intersection a & b creates a new set containing the shared value 3. The union a | b creates a new set containing 1, 2, 3, and 4. The membership test 3 in common returns True. The sorted() calls display the common and combined elements in ascending order.
Note
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Expecting a set to preserve duplicate values.
Why it happens: Sets keep only unique elements, so repeated values collapse into a single element.
Key takeaway: Sets store distinct elements only. Use a list or another suitable collection if repeated occurrences must be preserved.
#2 Using {} to create an empty set.
Why it happens: The literal {} creates an empty dictionary; use set() to create an empty set.
Key takeaway: Use set() for an empty set. Empty braces {} create a dictionary.
#3 Assuming that a set has indexes or a guaranteed element order.
Why it happens: Sets are unordered collections and do not support positional indexing; convert to a sorted sequence if a stable order is required.
Key takeaway: Sets are unordered and do not support indexing or slicing. Convert the set to a sorted list when predictable order is needed.
#4 Confusing union with intersection.
Why it happens: Union includes elements from either set, while intersection includes only elements present in both.
Key takeaway: Union (|) combines all distinct elements. Intersection (&) keeps only the elements shared by both sets.
#5 Assuming a - b and b - a produce the same result.
Why it happens: Set difference is directional: a - b contains elements in a that are not in b, so reversing the operands can change the result.
Key takeaway: Difference is directional. The left-hand set determines which elements are considered before values in the right-hand set are excluded.
#6 Using remove() when the element might not exist.
Why it happens: remove(value) raises KeyError if the element is absent; use discard(value) when absence is an acceptable case.
Key takeaway: Use discard() if a missing element should be ignored, or check membership before calling remove().
#7 Trying to add a list to a set.
Why it happens: A list is unhashable and cannot be a set element; use immutable hashable values such as tuples of hashable elements when appropriate.
Key takeaway: Set elements must be hashable. A list is unhashable, so use individual hashable elements or a tuple of hashable values if the grouped values must form one element.
#8 Confusing union() with update().
Why it happens: union() returns a new set, while update() mutates the existing set in place and returns None.
Key takeaway: union() returns a new set, whereas update() adds elements to the existing set.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a set in Python, and when would you use one?
Q2:What is the difference between union and intersection?
Q3:Why is set difference directional?
Q4:What is symmetric difference?
Q5:What is the difference between remove() and discard()?
Q6:Can a set contain a list? Why or why not?
Q7:What is the difference between union() and update()?
Key takeaways
- Sets store distinct, hashable elements and do not guarantee a positional order.
- Use set() to create an empty set; {} creates an empty dictionary.
- Use in and not in for membership checks.
- Union (|) combines all distinct elements, while intersection (&) keeps shared elements.
- Difference (-) keeps elements from the left-hand set that are absent from the right-hand set.
- Symmetric difference (^) keeps elements that occur in exactly one of the two sets.
- add() inserts one element, update() adds elements from an iterable, remove() raises KeyError for a missing value, and discard() safely ignores a missing value.
- Use sorted() when you need predictable ordered output from a set.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: