0
0
Pythonprogramming~20 mins

Adding and removing set elements in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Set Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
A{1, 2, 3, 4}
B{1, 2, 3, 4, 2}
C{4}
DError: cannot add duplicate elements
Attempts:
2 left
๐Ÿ’ก Hint
Remember that sets do not allow duplicates.
โ“ Predict Output
intermediate
2: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)
AKeyError
B{10, 20, 30}
CNone
DSet unchanged: {10, 20, 30}
Attempts:
2 left
๐Ÿ’ก Hint
Check what remove() does if the element is missing.
โ“ Predict Output
advanced
2: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)
A{5, 6, 7}
B{5, 6, 7, 10}
CKeyError
D{5, 7}
Attempts:
2 left
๐Ÿ’ก Hint
Discard does not raise an error if the element is missing.
๐Ÿง  Conceptual
advanced
2: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?
Aremove()
Bdiscard()
Cpop()
Dclear()
Attempts:
2 left
๐Ÿ’ก Hint
One method raises an error if the element is missing, the other does not.
โ“ Predict Output
expert
3: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)
A{3}
B{1, 2, 3, 4}
C{2, 3}
D{1, 3}
Attempts:
2 left
๐Ÿ’ก Hint
Track each add and remove step carefully.