Practice: Set Methods
Q1. Add an item
Start with s = {1, 2} and add 3. Print the sorted set.
Goal: Use add.
Q2. Add many
Start with an empty set and add 4, 5 and 6 from a list in one call. Print the length.
Goal: Use update.
Q3. Safe removal
Remove 5 from {1, 2, 3} without raising an error, then print the sorted set.
Goal: Use discard.
Q4. Intersection method
Print the sorted result of {1, 2, 3, 4}.intersection([2, 4, 6]).
Goal: Method with a list.
Q5. In-place difference
Remove the items of {2, 3} from s = {1, 2, 3, 4} in place and print the sorted set.
Goal: In-place update.
Q6. Superset test
Print whether {1, 2, 3} is a superset of {2, 3}.
Goal: Use issuperset.
Q7. Independent copy
Copy set a = {1, 2}, add 3 to the copy only, then print the sorted a and the sorted copy on two lines.
Goal: Copy a set.
Q8. Update with a string
What does this print?
s = set()
s.update('ab')
print(sorted(s))Goal: String is iterable.
Q9. Add twice
What does this print?
s = {1}
s.add(1)
s.add(2)
print(len(s))Goal: Unique items.
Q10. Return value
What does this print?
s = {1}
print(s.add(2))Goal: Methods return None.
Q11. Single pop
What does this print?
s = {'x'}
print(s.pop(), len(s))Goal: pop with one item.
Q12. Symmetric method
What does this print?
print(sorted({1, 2, 3}.symmetric_difference({3, 4})))Goal: Symmetric difference.
Q13. Copy vs alias
What does this print?
a = {1}
b = a
c = a.copy()
a.add(2)
print(len(b), len(c))Goal: Alias vs copy.
Q14. Empty subset
What does this print?
print(set().issubset({1}), {1}.issubset({1}))Goal: Subset edge cases.
Q15. Union many
What does this print?
print(sorted({1}.union({2}, [3], (4,))))Goal: Union with many.
Q16. Fix remove
This code raises KeyError. Fix it so it prints [1, 2].
s = {1, 2}
s.remove(3)
print(sorted(s))Goal: remove vs discard.
Q17. Fix the None
This code prints None. Fix it so it prints [1, 2, 3].
s = {1, 2}
s = s.update([3])
print(sorted(s))Goal: In-place return.
Q18. Fix add list
This code raises TypeError. Fix it so it prints [1, 2, 3].
s = {1}
s.add([2, 3])
print(sorted(s))Goal: add vs update.
Q19. Remove vs discard
Explain the difference between remove and discard.
Goal: Know the difference.
Q20. Why arbitrary pop
Why does pop on a set remove an arbitrary item?
Goal: Understand pop.