Python Sets
Overview
Python sets are un-ordered. Care has to be taken to make sure you don't assume sets to be ordered like lists are. In this sense they behave similar to dictionary which is also unordered.
Creating A Set
You create a new set in Python with the call set()
, passing in a list of values you want in your set:
my_set = set([1, 2, 3, 4])
You can also create a set using set literal syntax:
my_set = { 1, 2, 3, 4 }
Set literal syntax looks very similar to dictionary literal syntax (which also uses {
/}
), except rather than key/value pairs there is just a single value. Set literal syntax is faster than set()
call above as Python doesn't have to create a list first.
Set Operations
Add
You can use the .add()
function to add a single element to a set. If it already exists in the set, this function does nothing.
A = { 1, 2, 3 }
A.add(4)
print(A)
# stdout: {1, 2, 3, 4}
If you want to add multiple elements at the same time, see the .union()
function below.
Union
A set union can be done either with .union()
or |
. It returns a set of all elements that are in either A or B:
A = { 1, 2, 3, 4 }
B = { 3, 4, 5, 6 }
C = A | B
print(C)
# stdout: {1, 2, 3, 4, 5, 6}
The union returns a new set and does not modify the input sets. To perform a union but to modify inplace (which can potentially save memory and increase performance), use update()
:
A = { 1, 2, 3, 4 }
B = { 3, 4, 5, 6 }
A.update(B)
print(A)
Intersection
A set intersection can be done with either .intersection()
or &
. It returns a set of only the elements which are in both A and B:
A = { 1, 2, 3, 4 }
B = { 3, 4, 5, 6 }
C = A & B
print(C)
# stdout: {3, 4}
To perform an inplace intersection:
A = { 1, 2, 3, 4 }
B = { 3, 4, 5, 6 }
A.intersection_update(B)
print(A)
# stdout: {3, 4}