xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Sets

Data structures4 min readLesson 3 of 3

A set stores unique items with no order.

python
letters = {"a", "b", "a"}   # {'a', 'b'}
"a" in letters              # fast

Set algebra is the reason to reach for one:

python
a = {1, 2, 3}
b = {3, 4}
a | b   # union        {1, 2, 3, 4}
a & b   # intersection {3}
a - b   # difference   {1, 2}

Deduplicating a list is one line: list(set(items)). Remember the order is lost; use dict.fromkeys(items) when order matters.

Sets need hashable members, so a list of lists cannot become a set. Convert the inner lists to tuples first.