Set Methods
add, remove, discard, pop
Interview Relevant: Set manipulation
Set Methods
Methods for modifying sets.
Code Examples
Set modification methods.
python
1s = {1, 2, 3}
2
3# Add element
4s.add(4) # {1, 2, 3, 4}
5
6# Remove element
7s.remove(2) # Raises KeyError if not found
8s.discard(2) # No error if not found
9
10# Pop (remove and return arbitrary element)
11item = s.pop()
12
13# Clear all
14s.clear()
15
16# Update (add multiple)
17s = {1, 2}
18s.update([3, 4]) # {1, 2, 3, 4}
19s |= {5, 6} # {1, 2, 3, 4, 5, 6}
20
21# Intersection update
22s = {1, 2, 3, 4}
23s &= {2, 3, 5} # {2, 3}
24s.intersection_update({2, 5})
25
26# Difference update
27s = {1, 2, 3, 4}
28s -= {2, 3} # {1, 4}