Skip to content

Using Sets in Python

Python has a set data structure built-in.

Declaring a set

mySet = {1.0, "Python", (4, 5, 6)}
print(mySet)

Sets do not have duplicates, not can they contain mutable items such as lists, but a set can be formed from a list:

# no duplicates, this will output {1, 2, 3, 4}
mySet = {1,1,2,2,2,3,4,4}
print(mySet)

# this line will cause an error as the set contains a list
# eSet = {1, 2, [3, 4]}

# a set can be made, cast, from a list
eSet = set([1, 2, 3])
print(eSet)

Adding elements to a set

Empty sets are created using the set() function on a dictionary with no arguments and elements are added to the set object using the methods add() for a single element and update() for multiple:

# declare an empty set
s = {}
# check the data type ...
print(type(s))
s = set()
#check the data type again ..
print(type(s))

# add an element
s.add(42)
print(s)
# add multiple elements
s.update([6, 98])
print(s)

Removing elements from a set

Elements can be removed using either remove() which raises an error if the element can not be found, or discard(), or to clear all elements use clear().

Python permits set operations as well.

Set Operations: Union

Use the "|" operator, or call the union method on a set object:

1
2
3
4
5
6
7
8
A = {1, 2, 3}
B = {4, 5, 6}

print{A | B}        # {1, 2, 3, 4, 5, 6}

C = {}              # declare a new set
C = set()
C = A.union(B)      # populate with A union B

Set Operations: Intersection

Use the "&" operator, or call the intersection method:

1
2
3
4
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A & B)

Take it further

There are a lot of other built in methods and functions for processing sets and you are encouraged to explore further, see for example the following: