Sets

NoteWhat is a set?

A set is an unordered collection of unique and immutable objects.

NoteWhat does it mean that sets are unordered collections?

By design, set is a data structure with undefined element ordering (see Snippet 4.22 — the outcome included in line 6 does not follow any particular order).

NoteWhat does it mean that sets have unique items?

By definition, an item appears only once in a set, no matter how many times it is added (see Snippet 4.22, line 2 Vs. line 7).

# create a list
>>> L = ["a", "a", "b", "c", "c"]

# get a set from L
>>> S = set(L)
>>> print(S)
{"b", "a", "c"}
NoteWhy should I use sets?

Sets made this way support common mathematical set operations (see Snippet 4.23). Hence, they have a variety of applications, especially in numeric and database-focused work.

# create two sets
>>> X = set(["a", "b", "c"])
>>> Y = set(["c", "d", "e"])

# set difference
>>> X - X
set()
>>> X - Y
{"a", "b"}

# union
>>> X | Y
{"a", "b", "c", "d", "e"}

# intersection
>>> X & Y
{"c"}

# superset
>>> X > Y
False

# subset
>>> X < Y
False