Challenge - 5 Problems
Set Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
What is the output of this code adding elements to a set?
Consider the following Python code that adds elements to a set. What will be printed?
Python
s = {1, 2, 3}
s.add(4)
s.add(2)
print(s)Attempts:
2 left
๐ก Hint
Remember that sets do not allow duplicates.
โ Incorrect
Adding 4 to the set adds a new element. Adding 2 again does nothing because 2 is already in the set. So the set contains {1, 2, 3, 4}.
โ Predict Output
intermediate2:00remaining
What happens when removing an element not in the set?
What will happen when this code runs?
Python
s = {10, 20, 30}
s.remove(40)
print(s)Attempts:
2 left
๐ก Hint
Check what remove() does if the element is missing.
โ Incorrect
The remove() method raises a KeyError if the element is not found in the set.
โ Predict Output
advanced2:00remaining
What is the output after using discard on a set?
Look at this code and decide what it prints.
Python
s = {5, 6, 7}
s.discard(6)
s.discard(10)
print(s)Attempts:
2 left
๐ก Hint
Discard does not raise an error if the element is missing.
โ Incorrect
Discard removes 6 from the set. Discarding 10 does nothing because 10 is not in the set and no error is raised.
๐ง Conceptual
advanced2:00remaining
Which method safely removes an element without error if missing?
You want to remove an element from a set but avoid errors if it is not present. Which method should you use?
Attempts:
2 left
๐ก Hint
One method raises an error if the element is missing, the other does not.
โ Incorrect
discard() removes the element if present but does nothing if missing, so it is safe to use.
โ Predict Output
expert3:00remaining
What is the final set after these operations?
Analyze the code below and determine the final content of the set.
Python
s = set() s.add(1) s.add(2) s.add(3) s.remove(2) s.discard(4) s.add(2) s.remove(1) print(s)
Attempts:
2 left
๐ก Hint
Track each add and remove step carefully.
โ Incorrect
Initially empty set. Add 1,2,3 โ {1,2,3}. Remove 2 โ {1,3}. Discard 4 (no error) โ {1,3}. Add 2 โ {1,2,3}. Remove 1 โ {2,3}.