Understanding Python Sets
Sets are a built-in Python data type that represents an **unordered collection of unique elements**.
Example:
my_set = {1, 2, 2, 3}
print(my_set) # Output: {1, 2, 3} (duplicates removed, order not guaranteed)
Key takeaways:
4
to the set numbers = {1, 2, 3}
?Adding elements to a set
Sets have an add()
method to insert a single element. Since sets are unordered and contain only unique items, you cannot use +
,
insert()
, or append()
.
Option 1 – Incorrect: Sets do not support the +
operator.
Option 2 – Incorrect: insert()
is a list method, not a set method.
Option 3 – Correct: add(4)
adds the element to the set.
Option 4 – Incorrect: append()
does not exist for sets.
Example:
numbers = {1, 2, 3}
numbers.add(4)
print(numbers) # Output: {1, 2, 3, 4} (order may vary)
Key takeaways:
Use add()
to insert a single element into a set.
Sets are unordered; the new element may not appear at the “end”.
Adding an element that already exists does not raise an error; duplicates are ignored.
2
from the set numbers = {1, 2, 3}
without raising an error if the element does not exist?Removing elements from a set safely
Sets provide two methods to remove elements: remove()
and discard()
. The difference is important:
remove()
will raise a KeyError
if the element does not exist.discard()
removes the element if it exists and does nothing if it doesn’t.pop()
removes and returns an arbitrary element; cannot specify a value.delete()
is not a valid set method.Example:
numbers = {1, 2, 3}
numbers.discard(2) # Removes 2 safely
numbers.discard(4) # Does nothing, no error
print(numbers) # Output: {1, 3} (order may vary)
Key takeaways:
discard()
to remove elements safely without worrying about errors.remove()
if you want an error to indicate the element was missing.3
is a member of the set numbers = {1, 2, 3, 4}
?Checking membership in a set
To check if an element exists in a set, use the in
keyword. This is simple and Pythonic.
contains()
method.has()
is not a valid set method.check()
does not exist for sets.3 in numbers
returns True
if the element exists.Example:
numbers = {1, 2, 3, 4}
if 3 in numbers:
print("Found")
else:
print("Not Found")
# Output:
# Found
Key takeaways:
in
for membership tests with sets.contains()
or has()
do not exist in Python sets.
numbers = [1, 2, 2, 3, 4, 4, 5]
Creating a set to remove duplicates
Converting a list to a set automatically removes duplicate elements, since sets only store unique values.
set(numbers)
creates a set and removes duplicates.remove_duplicates()
is not a valid method in Python.Example:
numbers = [1, 2, 2, 3, 4, 4, 5]
numbers_set = set(numbers)
print(numbers_set) # Output: {1, 2, 3, 4, 5} (order may vary)
Key takeaways:
set()
to remove duplicates efficiently.list(set(numbers))
.Difference between lists and sets
Understanding the distinction between lists and sets is crucial for choosing the right data structure:
Example:
my_list = [1, 2, 2, 3]
my_set = {1, 2, 2, 3}
print(my_list) # Output: [1, 2, 2, 3] (order maintained, duplicates allowed)
print(my_set) # Output: {1, 2, 3} (duplicates removed, order not guaranteed)
Key takeaways:
A
and B
?
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Finding intersection of two sets
The intersection of two sets contains only elements that exist in both sets. Python provides multiple ways to do this, including the &
operator and the intersection()
method.
+
operator is not valid for sets.A & B
returns elements common to both sets.union()
returns all elements from both sets, not just common ones.subtract()
is not a valid set method; the correct method for difference is difference()
.Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
intersection = A & B
print(intersection) # Output: {3, 4}
Key takeaways:
&
or intersection()
to find common elements between sets.|
or union()
to combine all elements.A
and B
(elements in A
but not in B
)?
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
Finding the difference between two sets
The difference of two sets returns elements that are in the first set but not in the second.
&
returns the intersection, not the difference.|
returns the union of the sets.A - B
returns elements only in A
and not in B
.difference_update()
modifies the original set A
in place and returns None
, so it’s not suitable if you want a new set.Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
diff = A - B
print(diff) # Output: {1, 2}
Key takeaways:
-
or difference()
to find elements in one set not present in another.difference_update()
modifies the set in place; -
returns a new set.A
is a subset of B
?
A = {1, 2}
B = {1, 2, 3, 4}
Checking if a set is a subset
A set A
is a subset of another set B
if all elements of A
are present in B
. Python provides the issubset()
method for this purpose.
&
returns the intersection, not a boolean subset check.|
returns the union of the sets.-
returns the difference, not a boolean result.A.issubset(B)
returns True
if all elements of A
are in B
.Example:
A = {1, 2}
B = {1, 2, 3, 4}
subset = A.issubset(B)
print(subset) # Output: True
Key takeaways:
issubset()
to verify if all elements of one set exist in another.issuperset()
and isdisjoint()
.A
and B
(elements in either A
or B
but not in both)?
A = {1, 2, 3}
B = {2, 3, 4}
Symmetric difference of two sets
The symmetric difference of two sets returns elements that are in either of the sets but not in both. Python provides the ^
operator or symmetric_difference()
method.
A ^ B
returns elements exclusive to each set.&
returns the intersection, i.e., elements in both sets.|
returns the union, i.e., all elements from both sets.A - B - B
is invalid logic and does not produce symmetric difference.Example:
A = {1, 2, 3}
B = {2, 3, 4}
sym_diff = A ^ B
print(sym_diff) # Output: {1, 4} (order may vary)
Key takeaways:
^
or symmetric_difference()
to find elements in either set but not both.Understanding frozensets in Python
A frozenset is similar to a set but **immutable**. This makes it suitable for use as a key in dictionaries or as elements of other sets.
Example:
fs = frozenset([1, 2, 3])
d = {fs: "immutable key"}
print(d) # Output: {frozenset({1, 2, 3}): 'immutable key'}
Key takeaways:
(4, 5)
to it?
s = {(1, 2), (2, 3)}
Adding tuples to a set
Sets can only contain hashable (immutable) elements. Tuples are immutable and hashable, so they can be added. Lists, however, are mutable and cannot be elements of a set.
[4, 5]
) to a set; raises TypeError
.append()
is not a valid method for sets.add((4, 5))
correctly adds the tuple to the set.update()
expects an iterable; update(4, 5)
raises TypeError
.Example:
s = {(1, 2), (2, 3)}
s.add((4, 5))
print(s) # Output: {(1, 2), (2, 3), (4, 5)}
Key takeaways:
add()
to insert a single element into a set.Using set comprehensions
Set comprehensions allow creating sets dynamically using an expression inside curly braces {}
. They automatically remove duplicates and generate a set.
Example:
squares = {x**2 for x in range(1, 7) if x % 2 == 0}
print(squares) # Output: {4, 16, 36} (order may vary)
Key takeaways:
{}
are used for set comprehension; square brackets []
create a list.A
or B
but not both, using the symmetric_difference()
method?
A = {1, 2, 3}
B = {2, 3, 4}
Using symmetric_difference() for sets
The symmetric_difference()
method returns elements that are in either set but not in both.
A.symmetric_difference(B)
returns {1, 4}, the elements exclusive to each set.union()
returns all elements from both sets.intersection()
returns only elements common to both sets.-
gives elements only in A
but not in B
, not the symmetric difference.Example:
A = {1, 2, 3}
B = {2, 3, 4}
sym_diff = A.symmetric_difference(B)
print(sym_diff) # Output: {1, 4} (order may vary)
Key takeaways:
symmetric_difference()
or ^
operator to find elements in either set but not both.symmetric_difference_update()
.A
by removing all elements that are present in set B
and then adds a new set of elements {10, 11}
?
A = {1, 2, 3, 4, 5, 6}
B = {2, 4, 6}
new_elements = {10, 11}
Updating sets with difference_update() and update()
This example demonstrates how to remove multiple elements from a set and then add new elements in a clean, efficient way.
+
operator cannot be used with sets; this raises a TypeError
.difference_update(B)
removes all elements from A
that exist in B
. Then, update(new_elements)
adds the new elements.remove(B)
expects a single element, not a set. add(new_elements)
would add the set as a single element.symmetric_difference(B)
returns elements not in both sets, which is different from removing elements of B
. Using union
works, but the first step is logically different from what’s intended.Example:
A = {1, 2, 3, 4, 5, 6}
B = {2, 4, 6}
new_elements = {10, 11}
# Remove elements of B
A.difference_update(B)
# Add new elements
A.update(new_elements)
print(A) # Output: {1, 3, 5, 10, 11} (order may vary)
Step-by-step reasoning:
Key takeaways:
difference_update()
modifies the original set by removing elements in another set.update()
adds multiple elements at once.Storing sets within sets
Regular sets in Python are mutable and unhashable. Since sets require their elements to be hashable, you cannot store a mutable set inside another set. This is where frozenset
comes in.
TypeError
.frozenset
is immutable and hashable, allowing it to be an element of another set.Example:
inner1 = frozenset({1, 2})
inner2 = frozenset({3, 4})
outer_set = {inner1, inner2}
print(outer_set) # Output: {frozenset({1, 2}), frozenset({3, 4})}
Key takeaways:
frozenset
whenever you need to store immutable sets inside another set.A
, B
, and C
(i.e., elements that appear in exactly one set)?
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = {1, 6, 7, 8}
Finding elements unique across multiple sets
This problem requires identifying elements that appear in exactly one of the sets. The solution involves using set difference and union operations.
(A - B - C) | (B - A - C) | (C - A - B)
finds elements exclusive to each set and then combines them. This ensures only elements present in exactly one set are included.A & B & C
returns elements common to all three sets, not unique elements.(A | B | C) - (A & B & C)
returns elements that are not in all three sets, which may include elements present in two sets, not just one.difference(A, B, C)
is invalid syntax; it does not compute unique elements.Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = {1, 6, 7, 8}
unique_elements = (A - B - C) | (B - A - C) | (C - A - B)
print(unique_elements) # Output: {2, 5, 7, 8} (order may vary)
Step-by-step reasoning:
Key takeaways:
-
) to remove elements present in other sets.|
) to combine exclusive elements from multiple sets.A
, B
, and C
?
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = {1, 4, 6, 7}
Counting elements present in exactly two sets
To find elements that are in exactly two of the three sets, we need to:
A & B & C
gives elements common to all three sets, not exactly two.((A & B) - C) | ((A & C) - B) | ((B & C) - A)
correctly computes elements in exactly two sets.union()
returns all elements from all sets, not the count for exactly two.Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = {1, 4, 6, 7}
count = len(((A & B) - C) | ((A & C) - B) | ((B & C) - A))
print(count) # Output: 3 (elements 1, 3, 6 appear in exactly two sets)
Step-by-step reasoning:
Key takeaways:
A
, B
, and C
(i.e., elements unique to each set)?
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = {1, 4, 6, 7}
Finding elements unique to each set
The goal is to identify elements that are present in only one set and not shared with any other. This requires subtracting the other sets from each set and then taking the union.
A & B & C
returns elements common to all three sets.(A | B | C) - (A & B & C)
returns elements not in all three sets, but it may include elements present in two sets.(A & B) | (B & C) | (A & C)
returns elements present in at least two sets, not unique elements.(A - B - C) | (B - A - C) | (C - A - B)
correctly computes elements unique to each set.Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = {1, 4, 6, 7}
unique_elements = (A - B - C) | (B - A - C) | (C - A - B)
print(unique_elements) # Output: {2, 5, 7} (order may vary)
Step-by-step reasoning:
Key takeaways:
A
, B
, and C
?
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = {1, 4, 6, 7}
Finding elements present in at least two sets
This problem requires identifying elements that are shared by two or more sets. To achieve this:
((A & B) | (B & C) | (A & C))
gives all elements appearing in at least two sets.Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = {1, 4, 6, 7}
result = ((A & B) | (B & C) | (A & C))
print(result) # Output: {1, 3, 4, 6} (order may vary)
Step-by-step reasoning:
Key takeaways:
Practicing Python Sets? Don’t forget to test yourself later in our Python Quiz.
Sets are one of the most powerful Python data structures, and at Solviyo, we believe mastering them is essential for anyone looking to improve their Python programming skills. That’s why we’ve created practical Python exercises and interactive Python MCQs that make learning sets easy, engaging, and hands-on. Sets allow us to store unique items, perform fast membership tests, and execute important set operations like union, intersection, and difference efficiently.
We begin with the basics. In our Python sets exercises, you’ll learn how to create sets, add or remove elements, and understand the uniqueness property that separates sets from lists and tuples. Our Python MCQs are designed to reinforce your understanding, so you can test yourself as you learn. This combination of exercises and MCQs ensures a deeper grasp of Python sets than theory alone.
Next, we focus on set operations. You’ll practice union, intersection, difference, and symmetric difference, which are essential for solving real-world problems such as merging datasets, removing duplicates, and comparing collections. These exercises simulate real-world Python programming tasks, making them perfect for learners preparing for coding interviews, academic projects, or professional development.
We also cover common mistakes and best practices in using sets, including why you can’t index sets like lists and how to work efficiently with mutable and immutable elements. By combining hands-on exercises with targeted MCQs, we ensure that learners not only memorize Python syntax but also understand when and why to use sets in real applications.
At Solviyo, we designed these exercises and MCQs to strengthen both your conceptual knowledge and practical Python programming skills. By the end of this section, you’ll confidently manipulate Python sets, perform complex operations, and apply them in real-world scenarios. Whether you’re a beginner, intermediate, or professional looking to improve your Python coding skills, practicing sets with Solviyo is an excellent way to build a strong foundation in Python data structures.
Start practicing Python sets today with Solviyo’s interactive exercises and MCQs, and take your Python programming skills to the next level while mastering one of the most essential Python data structures for real-world coding challenges.