Sets Cheatsheet

Complete Python Sets cheatsheet with clear examples for quick revision

1

.add(item)

Adds a single item to a set.

example
s1 = {12, 34, 23, 56, 78, 45}
s1.add(3.14)  # {12, 34, 23, 56, 78, 45, 3.14}
2

.update(iterable)

Updates a set by adding elements from an iterable (list, set, tuple).

example
s1 = {12, 34, 23, 56, 78, 45}
s1.update([1.23, 4.20, 5.67])  # {12, 1.23, 23, 34, 4.20, 45, 56, 78, 5.67}
3

.union(set)

Returns a new set consisting of items from both sets.

example
s1 = {12, 34, 23, 56, 78, 45}
s2 = {1.23, 4.20, 5.67}
s1.union(s2)  # {12, 1.23, 23, 34, 4.20, 45, 56, 78, 5.67}
4

.remove(item)

Removes a specific item from the set. (Raises KeyError if the item is not present.)

example
s1 = {12, 34, 23, 56, 78, 45}
s1.remove(56)  # {12, 34, 23, 78, 45}
5

.discard(item)

Removes a specific item from the set. (Does nothing if the item is not present.)

example
s1 = {12, 34, 23, 56, 78, 45}
s1.discard(34)  # {12, 23, 56, 78, 45}
6

.pop()

Removes and returns an arbitrary item from the set.

example
s1 = {12, 34, 23, 56, 78, 45}
s1.pop()  # removes and returns an arbitrary item
# resulting set might be {12, 34, 23, 56, 45} (actual item removed is arbitrary)
7

.clear()

Removes all the items from the set.

example
s1 = {12, 34, 23, 56, 78, 45}
s1.clear()  # set()
8

.copy()

Returns a shallow copy of the set.

example
s1 = {12, 34, 23, 56, 78, 45}
s2 = s1.copy()  # s2 = {12, 34, 23, 56, 78, 45}
9

.intersection(set)

Returns a new set with items common to both sets.

example
s1 = {12, 34, 23, 56, 78, 45}
s2 = {1, 2, 34, 56, 78, 9, 11}
s1.intersection(s2)  # {34, 56, 78}
10

.difference(set)

Returns a new set with the items in the first set but not in the second.

example
s1 = {12, 34, 23, 56, 78, 45}
s2 = {1, 2, 34, 56, 78, 9, 11}
s1.difference(s2)  # {12, 23, 45}
11

.symmetric_difference(set)

Returns a new set with items that are in either set but not in both (uncommon items).

example
s1 = {12, 34, 23, 56, 78, 45}
s2 = {1, 2, 34, 56, 78, 9, 11}
s1.symmetric_difference(s2)  # {12, 23, 45, 1, 2, 9, 11}