Data Science Portfolio

Sets

Basics

Create a set using curly braces

pets = {'dog', 'cat', 'parrot', 'cat', 'dog', 'rabbit', 'hamster', 'dog'}

# Confirm that duplicates are removed
print(pets)
{'parrot', 'hamster', 'dog', 'cat', 'rabbit'}

Set Operations

Create sets from two words

a = set('calcariferous')
b = set('demagogue')

Unique letters in a

a
{'a', 'c', 'e', 'f', 'i', 'l', 'o', 'r', 's', 'u'}

Unique letters in b

b
{'a', 'd', 'e', 'g', 'm', 'o', 'u'}

Letters in a but not in b

a - b
{'c', 'f', 'i', 'l', 'r', 's'}

Letters in a or b or both

a | b
{'a', 'c', 'd', 'e', 'f', 'g', 'i', 'l', 'm', 'o', 'r', 's', 'u'}

Letters in both a and b

a & b
{'a', 'e', 'o', 'u'}

Letters in a or b but not both

a ^ b
{'c', 'd', 'f', 'g', 'i', 'l', 'm', 'r', 's'}