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 & B returns 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 is difference().
Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
intersection = A & B
print(intersection) # Output: {3, 4}
Key takeaways:
Use & or intersection() to find common elements between sets.
Use | or union() 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 - B returns elements only in A and not in B.
Option 4 – Incorrect: 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:
Use - or difference() 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) 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:
Use issubset() to verify if all elements of one set exist in another.
Sets provide other relational methods like issuperset() and isdisjoint().
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 ^ B returns 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 - 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:
Use ^ or symmetric_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.
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; raises TypeError.
Option 2 – Incorrect: append() is not a valid method for sets.
Option 3 – Correct: add((4, 5)) correctly adds the tuple to the set.
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 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:
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 a TypeError.
Option 2 – Correct: First, difference_update(B) removes all elements from A that exist in B. 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 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:
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: frozenset is 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).
Use frozenset whenever 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 setsA, 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 & C returns 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 setsA, 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 & C gives 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 & C returns 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 setsA, 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.
Quick Recap of Python Sets Concepts
If you are not clear on the concepts of Sets, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.
What is a Python Set?
A Python set is an unordered collection of unique elements. Sets do not allow duplicates, and the elements cannot be accessed by index. Elements must be hashable (immutable). Sets are commonly used to store distinct items and perform mathematical set operations.
Creating Python Sets
You can create a set using curly braces or the set() constructor:
# Using curly braces
gems = {"onyx", "opal", "amethyst", "jade"}
# Using the set() constructor
numbers = set([11, 22, 33, 44])
letters = set("abracadabra") # duplicates automatically removed
# Empty set
empty_set = set()
Accessing / Iterating Elements of Python Set
You can loop through a set and check membership:
exotic_fruits = {"durian", "rambutan", "salak", "longan"}
for fruit in exotic_fruits:
print(fruit)
# Check membership
if "durian" in exotic_fruits:
print("Durian is in the set")
Adding and Removing Elements in Python Set
You can add single or multiple elements and remove them safely:
planets = {"Mercury", "Venus", "Earth"}
planets.add("Mars")
planets.update(["Jupiter", "Saturn"])
planets.remove("Venus")
planets.discard("Pluto") # safe even if not present
print(planets)
Set Operations: Union, Intersection, Difference, Symmetric Difference
Sets support mathematical operations to combine or compare elements:
A = {"lion", "tiger", "leopard"}
B = {"tiger", "cheetah", "jaguar"}
print(A.union(B)) # {'lion', 'tiger', 'leopard', 'cheetah', 'jaguar'}
print(A & B) # {'tiger'} — intersection
print(A - B) # {'lion', 'leopard'} — difference
print(A ^ B) # {'lion', 'leopard', 'cheetah', 'jaguar'} — symmetric difference
Removing Duplicates from a List Using a Set
Sets can be used to quickly remove duplicates from a list:
Practicing Python Sets? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python Sets Exercises
Welcome to Solviyo’s Python Sets exercises, designed to help you master one of Python’s most powerful and versatile data structures. Sets allow you to store unique items, perform fast membership tests, and execute operations like union, intersection, and difference efficiently. These exercises provide hands-on practice and interactive MCQs to make learning practical and engaging.
What You Will Learn
In this set of Python Sets exercises, you will explore:
Creating sets and understanding their uniqueness compared to lists and tuples.
Adding and removing elements, and working with mutable and immutable set items.
Performing essential set operations including union, intersection, difference, and symmetric difference.
Applying sets to solve real-world problems such as merging datasets, removing duplicates, and comparing collections.
Understanding common mistakes, such as indexing sets, and best practices for efficient set usage.
Reinforcing learning through interactive MCQs alongside practical exercises.
Developing confidence in applying Python sets in coding interviews, projects, and professional tasks.
Why Learning Python Sets Matters
Sets are an essential part of Python programming for handling collections of unique items efficiently. Mastering sets allows you to perform complex data operations quickly, write cleaner code, and tackle real-world programming challenges with confidence. Understanding set operations prepares you for advanced topics and coding interviews.
Start Practicing Python Sets Today
By completing these exercises, you will gain hands-on experience in manipulating Python sets and applying them in practical scenarios. Each exercise includes detailed explanations to help you understand the reasoning behind solutions. Start practicing Python Sets exercises now, and strengthen your Python programming skills while mastering this essential data structure.
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.