Improve your Python skills by finding and fixing common mistakes in sets code. Practice debugging set operations, membership, and manipulation with beginner-friendly exercises and solutions.
Topic: sets
Fix the code that attempts to create a set with duplicate elements.
my_set = {1, 2, 2, 3, 3, 3}
print(my_set)
Hint: 💡 Sets automatically handle duplicates - is there actually a mistake here?
Issue: There is no mistake - the code works as intended (sets remove duplicates)
# The original code is actually correct
my_set = {1, 2, 2, 3, 3, 3}
print(my_set) # Output will be {1, 2, 3}
Fix the attempt to create an empty set.
empty_set = {}
print(type(empty_set))
Hint: 💡 What does {} actually create in Python?
Issue: {} creates an empty dictionary, not an empty set
empty_set = set() # Correct way to create empty set
print(type(empty_set)) # Will show <class 'set'>
Fix the code that tries to add a list to a set.
my_set = {1, 2, 3}
my_set.add([4, 5])
Hint: 💡 Remember what types of elements can be added to sets.
Issue: Cannot add mutable list to a set (lists are unhashable)
my_set = {1, 2, 3}
my_set.add(4) # Add individual elements
# OR convert to tuple if you need to add multiple items
my_set.add(tuple([4, 5]))
Fix the set operation that's supposed to find elements in set1 but not in set2.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
difference = set1.intersection(set2)
Hint: 💡 Check which set method finds the difference between sets.
Issue: Using intersection() instead of difference()
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
difference = set1.difference(set2) # Correct method for set difference
# Alternatively: difference = set1 - set2
Fix the set comprehension that's not producing the expected output.
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_squares = [x**2 for x in numbers if x not in unique_squares]
Hint: 💡 There are multiple issues here - both with the approach and syntax.
Issue: 1. Using list comprehension brackets [] instead of set comprehension {} 2. Trying to reference unique_squares in its own comprehension 3. Not actually using set properties to handle uniqueness
numbers = [1, 2, 2, 3, 4, 4, 5]
# Simple solution using set properties:
unique_squares = {x**2 for x in numbers}
# Or alternatively:
unique_squares = set(x**2 for x in numbers)
Fix the code that attempts to use a set as a dictionary key.
my_dict = {}
my_set = {1, 2, 3}
my_dict[my_set] = "value"
Hint: 💡 Only immutable types can be dictionary keys.
Issue: Regular sets are mutable and cannot be dictionary keys
my_dict = {}
my_set = frozenset({1, 2, 3}) # Convert to frozenset
my_dict[my_set] = "value" # Now works because frozenset is immutable
Tutorials, Roadmaps, Bootcamps & Visualization Projects