Skip to content
PythonWorking with Collectionsbeginner18 min read

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

Duplicate values are stored only once
python
numbers = {1, 2, 2, 3, 3, 3}
print(sorted(numbers))
print(len(numbers))
Output
[1, 2, 3] 3

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

A set removes duplicate values, not the original collection itself. Converting a list to a set creates a separate collection and does not mutate the list.

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

Membership testing
python
available = {'tea', 'water'}
print('tea' in available)
print('coffee' in available)
print('coffee' not in available)
Output
True False True

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

Do not use indexing such as values[0] on a set. If you need a predictable first element, choose an appropriate ordering, for example sorted(values)[0], and handle the case where the set is empty.

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

Union using the | operator
python
a = {1, 2, 3}
b = {3, 4}
print(sorted(a | b))
Output
[1, 2, 3, 4]

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

Think of union as 'everything from either group, without duplicates.'

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

Intersection using the & operator
python
a = {1, 2, 3}
b = {3, 4}
print(sorted(a & b))
Output
[3]

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

Think of intersection as 'what both groups share.'

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

Difference using the - operator
python
a = {1, 2, 3}
b = {3, 4}
print(sorted(a - b))
print(sorted(b - a))
Output
[1, 2] [4]

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

Remember that a - b is not generally the same as b - a. Symmetric difference, a ^ b, is the set of values that are in exactly one of the two sets.

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 an element
python
numbers = {1, 2}
numbers.add(3)
numbers.add(2)
print(sorted(numbers))
Output
[1, 2, 3]

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

remove() raises KeyError when the requested element is absent, while discard() safely ignores a missing element. Also, do not try to add a list directly to a set because lists are unhashable.

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

Trace set operations in order
python
a = {1, 2, 3}
b = {3, 4}
common = a & b
combined = a | b
print(3 in common)
print(sorted(common))
print(sorted(combined))
Output
True [3] [1, 2, 3, 4]

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

Set operations such as |, &, -, and ^ return new sets. Methods such as update() modify the existing set instead.

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.

Incorrect Approach
script.py
python
Expecting a set to preserve duplicate values.
Correct Solution
script.py
python
Sets store distinct elements only. Use a list or another suitable collection if repeated occurrences must be preserved.

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.

Incorrect Approach
script.py
python
Using {} to create an empty set.
Correct Solution
script.py
python
Use set() for an empty set. Empty braces {} create a dictionary.

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.

Incorrect Approach
script.py
python
Assuming that a set has indexes or a guaranteed element order.
Correct Solution
script.py
python
Sets are unordered and do not support indexing or slicing. Convert the set to a sorted list when predictable order is needed.

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.

Incorrect Approach
script.py
python
Confusing union with intersection.
Correct Solution
script.py
python
Union (|) combines all distinct elements. Intersection (&) keeps only the elements shared by both sets.

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.

Incorrect Approach
script.py
python
Assuming a - b and b - a produce the same result.
Correct Solution
script.py
python
Difference is directional. The left-hand set determines which elements are considered before values in the right-hand set are excluded.

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.

Incorrect Approach
script.py
python
Using remove() when the element might not exist.
Correct Solution
script.py
python
Use discard() if a missing element should be ignored, or check membership before calling remove().

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.

Incorrect Approach
script.py
python
Trying to add a list to a set.
Correct Solution
script.py
python
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.

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.

Incorrect Approach
script.py
python
Confusing union() with update().
Correct Solution
script.py
python
union() returns a new set, whereas update() adds elements to the existing set.

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.

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?
Answer:
A set is an unordered collection of distinct, hashable elements. It is useful for removing duplicates, testing membership, and comparing groups using operations such as union, intersection, difference, and symmetric difference.
Q2:What is the difference between union and intersection?
Answer:
Union, written as a | b, includes all distinct elements from either set. Intersection, written as a & b, includes only elements present in both sets.
Q3:Why is set difference directional?
Answer:
a - b returns elements that belong to a but not to b. Reversing the operands changes which set supplies the starting elements, so b - a may produce a different result.
Q4:What is symmetric difference?
Answer:
Symmetric difference, written as a ^ b, returns elements that belong to either set but not to both. It excludes shared elements.
Q5:What is the difference between remove() and discard()?
Answer:
Both remove an element if it exists. remove() raises KeyError when the element is absent, while discard() does nothing when the element is absent.
Q6:Can a set contain a list? Why or why not?
Answer:
No. Set elements must be hashable, and lists are unhashable because they are mutable. A tuple containing only hashable elements can be used as a set element.
Q7:What is the difference between union() and update()?
Answer:
union() returns a new set containing the combined distinct elements. update() adds elements to the existing set and mutates it.

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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: