Sets#

Set Variables#

A set is an unordered collection of variables. By unordered it is meant a set that contains a and b is considered the same as a set that contains b and a.

A set is defined in Python using the familiar \{ \} List Notation,

pets = { "dog", "cat", "fish", "hamster", "snake" }

four_legs = { "dog", "cat", "hamster" }

swims = { "dog", "fish", "snake" }

warm_blooded = { "dog", "cat", "hamster" }

poets = { "byron", "shakespeare", "eliot" }

The examples on this page will refer to the above sets.

Set Operations#

Note

Before executing these commands, try working them out by hand first and see if your work agrees!

Cardinality#

The Cardinality of a set is found by calculating its length,

total_pets = len(pets)
print(total_pets)
Cardinality Solution

Output:

5

Union#

The Union of two sets is found by,

pets_or_poets = pets.union(poets)
print(pets_or_poets)
Union Solution

Output:

{‘snake’, ‘byron’, ‘shakespeare’, ‘eliot’, ‘fish’, ‘cat’, ‘dog’, ‘hamster’}

Important

Take note: set operations do not preserve the order of the sets. In technical terms, sets are not indexed. Notice the order of the set in the output is random.

Intersection#

The Intersection of two sets is found by,

four_legs_and_swims = four_legs.intersect(swims)
print(four_legs_and_swims)
Intersection Solution

Output:

{‘dog’}

Difference#

The Difference of two sets is found by,

swims_but_not_warmblooded = swims - warm_blooded
print(swims_but_not_warmblooded)
Difference Solution

Output:

{‘snake’}