Python sets

Attributes #

  • No duplicates in sets
  • Unordered
  • Immutable

Create a set #

set1 = {"A", "B", "C"}

Alternatively:

set1 set(("A", "B", "C"))

Can be made out of a list:

set_from_list = set(<some list>)

Length #

Get length of set:

len(some_set)

Union #

Combine sets.

# method 1
set1|set2

# method 2
set1.union(set2)

Intersection #

Find the parts of sets that overlap:

set1 = {"A", "B", "C"}
set2 = {"B", "D", "E"}

se1.intersection(set2) # {"B"}

Differences #

set1 = {"A", "B", "C"}
set2 = {"B", "D", "E"}

set1.difference(set2) # {"A", "C"}
set2.difference(set1) # {"D", "E"}

# all the differences
set1.symmetric_difference(set2) # {"A", "C", "D", "E"}

Resources: #