Python Sets Exercises
Python Sets Practice Questions
Which of the following statements about Python sets is correct?
Understanding Python Sets
Sets are a built-in Python data type that represents an **unordered collection of unique elements**.
- Option 1 – Incorrect: Sets cannot contain duplicates; any repeated elements are automatically removed.
- Option 2 – Incorrect: Sets are unordered; the insertion order is not preserved.
- Option 3 – Incorrect: Sets do not support indexing or slicing like lists.
- Option 4 – Correct: Sets automatically remove duplicates and do not maintain element order.
Example:
my_set = {1, 2, 2, 3}
print(my_set) # Output: {1, 2, 3} (duplicates removed, order not guaranteed)
Key takeaways:
- Sets store only unique elements.
- They are unordered, so indexing and slicing are not possible.
- Useful for membership checks, removing duplicates, and set operations.
Which of the following correctly adds an element 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:
Useadd()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.
Which of the following correctly removes the element 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:
- Option 1 – Incorrect:
remove()will raise aKeyErrorif the element does not exist. - Option 2 – Correct:
discard()removes the element if it exists and does nothing if it doesn’t. - Option 3 – Incorrect:
pop()removes and returns an arbitrary element; cannot specify a value. - Option 4 – Incorrect:
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:
- Use
discard()to remove elements safely without worrying about errors. - Use
remove()if you want an error to indicate the element was missing. - Sets are unordered; removing an element does not affect any “position”.
Which of the following correctly checks if 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.
- Option 1 – Incorrect: Sets do not have a
contains()method. - Option 2 – Incorrect:
has()is not a valid set method. - Option 3 – Incorrect:
check()does not exist for sets. - Option 4 – Correct:
3 in numbersreturnsTrueif the element exists.
Example:
numbers = {1, 2, 3, 4}
if 3 in numbers:
print("Found")
else:
print("Not Found")
# Output:
# Found
Key takeaways:
- Use
infor membership tests with sets. - This method is fast due to sets being implemented as hash tables.
- Other methods like
contains()orhas()do not exist in Python sets.
Which of the following snippets correctly creates a set from a list and removes duplicates?
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.
- Option 1 – Incorrect: Converting to a list again does not remove duplicates.
- Option 2 – Incorrect: You cannot directly convert a list to a dictionary without key-value pairs; this raises an error.
- Option 3 – Correct:
set(numbers)creates a set and removes duplicates. - Option 4 – Incorrect:
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:
- Use
set()to remove duplicates efficiently. - Sets are unordered; the original order of elements is not preserved.
- Converting back to a list is optional if you need a list without duplicates:
list(set(numbers)).
Which of the following correctly describes the difference between a list and a set in Python?
Difference between lists and sets
Understanding the distinction between lists and sets is crucial for choosing the right data structure:
- Option 1 – Correct: Lists maintain insertion order and allow duplicate elements, while sets are unordered and automatically remove duplicates.
- Option 2 – Incorrect: Lists are mutable, not immutable. Both lists and sets are mutable.
- Option 3 – Incorrect: Neither lists nor sets can be used as dictionary keys; only immutable types like tuples can.
- Option 4 – Incorrect: Lists can store numbers, strings, or any type of element, just like sets.
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:
- Use lists when order and duplicates matter.
- Use sets to ensure uniqueness and enable fast membership checks.
- Sets are implemented as hash tables, making operations like membership tests faster than lists.
Which of the following snippets correctly finds the intersection of two sets 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.
- Option 1 – Incorrect:
+operator is not valid for sets. - Option 2 – Correct:
A & Breturns elements common to both sets. - Option 3 – Incorrect:
union()returns all elements from both sets, not just common ones. - Option 4 – Incorrect:
subtract()is not a valid set method; the correct method for difference isdifference().
Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
intersection = A & B
print(intersection) # Output: {3, 4}
Key takeaways:
- Use
&orintersection()to find common elements between sets. - Use
|orunion()to combine all elements. - Set operations are fast due to the underlying hash table implementation.
Which of the following snippets correctly finds the difference between two sets 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.
- Option 1 – Incorrect:
&returns the intersection, not the difference. - Option 2 – Incorrect:
|returns the union of the sets. - Option 3 – Correct:
A - Breturns elements only inAand not inB. - Option 4 – Incorrect:
difference_update()modifies the original setAin place and returnsNone, 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:
- Use
-ordifference()to find elements in one set not present in another. difference_update()modifies the set in place;-returns a new set.- Sets provide fast operations for membership and comparisons.
Which of the following snippets correctly checks if 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.
- Option 1 – Incorrect:
&returns the intersection, not a boolean subset check. - Option 2 – Incorrect:
|returns the union of the sets. - Option 3 – Incorrect:
-returns the difference, not a boolean result. - Option 4 – Correct:
A.issubset(B)returnsTrueif all elements ofAare inB.
Example:
A = {1, 2}
B = {1, 2, 3, 4}
subset = A.issubset(B)
print(subset) # Output: True
Key takeaways:
- Use
issubset()to verify if all elements of one set exist in another. - Sets provide other relational methods like
issuperset()andisdisjoint(). - These methods return a boolean, making it easy to use in conditionals.
Which of the following snippets correctly performs a symmetric difference between sets 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.
- Option 1 – Correct:
A ^ Breturns elements exclusive to each set. - Option 2 – Incorrect:
&returns the intersection, i.e., elements in both sets. - Option 3 – Incorrect:
|returns the union, i.e., all elements from both sets. - Option 4 – Incorrect:
A - B - Bis 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:
- Use
^orsymmetric_difference()to find elements in either set but not both. - Set operators provide concise syntax for union, intersection, difference, and symmetric difference.
- Sets are ideal for mathematical set operations and fast membership checks.
Which of the following statements about frozensets in Python is correct?
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.
- Option 1 – Incorrect: Frozensets are immutable; you cannot add or remove elements.
- Option 2 – Incorrect: Frozensets are unordered; indexing and slicing are not supported.
- Option 3 – Incorrect: Frozensets do not maintain insertion order.
- Option 4 – Correct: Frozensets are immutable and hashable, so they can be used as dictionary keys or 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:
- Use frozensets when you need an immutable set.
- Frozensets are hashable, unlike regular sets.
- Operations like union, intersection, and difference are supported, but methods that modify the set are not.
Which of the following snippets correctly creates a set of tuples and adds a new tuple (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.
- Option 1 – Incorrect: Cannot add a list (
[4, 5]) to a set; raisesTypeError. - Option 2 – Incorrect:
append()is not a valid method for sets. - Option 3 – Correct:
add((4, 5))correctly adds the tuple to the set. - Option 4 – Incorrect:
update()expects an iterable;update(4, 5)raisesTypeError.
Example:
s = {(1, 2), (2, 3)}
s.add((4, 5))
print(s) # Output: {(1, 2), (2, 3), (4, 5)}
Key takeaways:
- Sets can only store hashable (immutable) elements like numbers, strings, and tuples.
- Use
add()to insert a single element into a set. - Mutable elements like lists or dictionaries cannot be added to a set.
Which of the following snippets correctly creates a set comprehension that contains squares of all even numbers from 1 to 6?
Using set comprehensions
Set comprehensions allow creating sets dynamically using an expression inside curly braces {}. They automatically remove duplicates and generate a set.
- Option 1 – Incorrect: This creates a list, not a set.
- Option 2 – Incorrect: Includes squares of all numbers from 1 to 6, not just even numbers.
- Option 3 – Incorrect: Converts a list of squares of all numbers to a set, not filtering even numbers.
- Option 4 – Correct: Uses set comprehension to include only squares of even numbers.
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:
- Set comprehensions are concise and automatically remove duplicates.
- Use conditions inside comprehension to filter elements.
- Curly braces
{}are used for set comprehension; square brackets[]create a list.
Which of the following snippets correctly finds elements present in either 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.
- Option 1 – Correct:
A.symmetric_difference(B)returns {1, 4}, the elements exclusive to each set. - Option 2 – Incorrect:
union()returns all elements from both sets. - Option 3 – Incorrect:
intersection()returns only elements common to both sets. - Option 4 – Incorrect:
-gives elements only inAbut not inB, 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:
- Use
symmetric_difference()or^operator to find elements in either set but not both. - This is useful for comparing sets and identifying unique differences.
- Operations do not modify the original sets unless using
symmetric_difference_update().
Which of the following snippets correctly updates set 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.
- Option 1 – Incorrect:
+operator cannot be used with sets; this raises aTypeError. - Option 2 – Correct: First,
difference_update(B)removes all elements fromAthat exist inB. Then,update(new_elements)adds the new elements. - Option 3 – Incorrect:
remove(B)expects a single element, not a set.add(new_elements)would add the set as a single element. - Option 4 – Incorrect:
symmetric_difference(B)returns elements not in both sets, which is different from removing elements ofB. Usingunionworks, 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:
- Initial set A: {1, 2, 3, 4, 5, 6}
- Removing elements present in B → {1, 3, 5}
- Adding new elements {10, 11} → {1, 3, 5, 10, 11}
Key takeaways:
difference_update()modifies the original set by removing elements in another set.update()adds multiple elements at once.- This combination is efficient for batch updates on sets.
Consider the following scenario: You want to store multiple immutable sets inside a set in Python. Which of the following statements is correct?
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.
- Option 1 – Incorrect: Regular sets are mutable and cannot be stored in another set; trying to do so raises
TypeError. - Option 2 – Incorrect: Lists are mutable and unhashable, so they cannot be stored in a set.
- Option 3 – Correct:
frozensetis immutable and hashable, allowing it to be an element of another set. - Option 4 – Incorrect: Tuples are hashable, but they do not behave like sets (no set operations such as union, intersection, or difference).
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:
- Use
frozensetwhenever you need to store immutable sets inside another set. - Regular sets and lists cannot be nested inside sets.
- Operations like union and intersection work with frozensets just like regular sets.
Which of the following snippets correctly finds all elements that are unique across three sets 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.
- Option 1 – Correct:
(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. - Option 2 – Incorrect:
A & B & Creturns elements common to all three sets, not unique elements. - Option 3 – Incorrect:
(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. - Option 4 – Incorrect:
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:
- A - B - C → elements only in A → {2}
- B - A - C → elements only in B → {5}
- C - A - B → elements only in C → {7, 8}
- Union of these → {2, 5, 7, 8}
Key takeaways:
- Use set difference (
-) to remove elements present in other sets. - Use set union (
|) to combine exclusive elements from multiple sets. - This technique is useful for advanced set operations in data analysis and algorithm design.
Which of the following snippets correctly counts the number of elements that appear in exactly two out of three 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:
- Find the intersection of each pair of sets.
- Remove elements that are also present in the third set.
- Combine all results to get all elements appearing in exactly two sets.
- Option 1 – Incorrect:
A & B & Cgives elements common to all three sets, not exactly two. - Option 2 – Incorrect: This returns elements not in all three sets, including those in only one set, which is incorrect.
- Option 3 – Correct:
((A & B) - C) | ((A & C) - B) | ((B & C) - A)correctly computes elements in exactly two sets. - Option 4 – Incorrect:
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:
- A & B → {3, 4}, remove C → {3}
- A & C → {1, 4}, remove B → {1}
- B & C → {4, 6}, remove A → {6}
- Union → {1, 3, 6}, length → 3
Key takeaways:
- Use pairwise intersections and differences to find elements in exactly N sets.
- Union combines the results efficiently.
- This method is helpful in advanced set-based data analysis and logic problems.
Which of the following snippets correctly finds all elements that are not shared by any two sets among 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.
- Option 1 – Incorrect:
A & B & Creturns elements common to all three sets. - Option 2 – Incorrect:
(A | B | C) - (A & B & C)returns elements not in all three sets, but it may include elements present in two sets. - Option 3 – Incorrect:
(A & B) | (B & C) | (A & C)returns elements present in at least two sets, not unique elements. - Option 4 – Correct:
(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:
- A - B - C → {2}
- B - A - C → {5}
- C - A - B → {7}
- Union → {2, 5, 7}
Key takeaways:
- Use set differences to isolate elements not shared with other sets.
- Union of these differences gives all elements unique to each set.
- This approach is useful in complex data comparison tasks where exclusivity matters.
Which of the following snippets correctly finds all elements that appear in at least two of the three sets 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:
- Compute the intersection of each pair of sets.
- Take the union of these intersections to get all elements appearing in at least two sets.
- Option 1 – Incorrect: This removes elements present in all three sets but still includes elements in only one set.
- Option 2 – Incorrect: Returns elements common to all three sets only.
- Option 3 – Correct:
((A & B) | (B & C) | (A & C))gives all elements appearing in at least two sets. - Option 4 – Incorrect: Returns elements unique to each set, not shared elements.
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:
- A & B → {3, 4}
- B & C → {4, 6}
- A & C → {1, 4}
- Union of all → {1, 3, 4, 6}
Key takeaways:
- Use pairwise intersections to identify elements shared across sets.
- Union of these intersections gives all elements appearing in two or more sets.
- This technique is useful in data analysis when identifying overlapping items across multiple datasets.
Explore More Python Exercises
You may also like these Python exercises:
Test Your Python Sets Knowledge
Practicing Python Sets? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python – Sets
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.