Practice: Set Methods

« Read the chapter

Q1. Add an item

BeginnerCoding

Start with s = {1, 2} and add 3. Print the sorted set.

Goal: Use add.

Q2. Add many

BeginnerCoding

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

BeginnerCoding

Remove 5 from {1, 2, 3} without raising an error, then print the sorted set.

Goal: Use discard.

Q4. Intersection method

IntermediateCoding

Print the sorted result of {1, 2, 3, 4}.intersection([2, 4, 6]).

Goal: Method with a list.

Q5. In-place difference

IntermediateCoding

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

IntermediateCoding

Print whether {1, 2, 3} is a superset of {2, 3}.

Goal: Use issuperset.

Q7. Independent copy

AdvancedCoding

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

BeginnerOutput

What does this print?

Code
s = set()
s.update('ab')
print(sorted(s))

Goal: String is iterable.

Q9. Add twice

BeginnerOutput

What does this print?

Code
s = {1}
s.add(1)
s.add(2)
print(len(s))

Goal: Unique items.

Q10. Return value

IntermediateOutput

What does this print?

Code
s = {1}
print(s.add(2))

Goal: Methods return None.

Q11. Single pop

IntermediateOutput

What does this print?

Code
s = {'x'}
print(s.pop(), len(s))

Goal: pop with one item.

Q12. Symmetric method

IntermediateOutput

What does this print?

Code
print(sorted({1, 2, 3}.symmetric_difference({3, 4})))

Goal: Symmetric difference.

Q13. Copy vs alias

AdvancedOutput

What does this print?

Code
a = {1}
b = a
c = a.copy()
a.add(2)
print(len(b), len(c))

Goal: Alias vs copy.

Q14. Empty subset

AdvancedOutput

What does this print?

Code
print(set().issubset({1}), {1}.issubset({1}))

Goal: Subset edge cases.

Q15. Union many

AdvancedOutput

What does this print?

Code
print(sorted({1}.union({2}, [3], (4,))))

Goal: Union with many.

Q16. Fix remove

BeginnerDebugging

This code raises KeyError. Fix it so it prints [1, 2].

Code
s = {1, 2}
s.remove(3)
print(sorted(s))

Goal: remove vs discard.

Q17. Fix the None

IntermediateDebugging

This code prints None. Fix it so it prints [1, 2, 3].

Code
s = {1, 2}
s = s.update([3])
print(sorted(s))

Goal: In-place return.

Q18. Fix add list

IntermediateDebugging

This code raises TypeError. Fix it so it prints [1, 2, 3].

Code
s = {1}
s.add([2, 3])
print(sorted(s))

Goal: add vs update.

Q19. Remove vs discard

BeginnerConceptual

Explain the difference between remove and discard.

Goal: Know the difference.

Q20. Why arbitrary pop

IntermediateConceptual

Why does pop on a set remove an arbitrary item?

Goal: Understand pop.