02. Sets

Sets are an unordered collection of items with no duplicates. If you add an element that already exists within a set, nothing happens. This can be great if you want to store a list of unique elements when order or count do not matter.

Sets in Math

In math, recall learning about sets and set theory, where the idea was to find similar or dissimilar members (or elements) of different groups. Visually, set theory was often viewed by Venn diagrams.

Set theory is often visually displayed as a venn diagram
Set theory is often visually displayed as a venn diagram.

Creating sets

To create a set, use the set()function, or just wrap a list of elements within curly braces ({}).

Sets can be created with any iterable object, such as a list, string, or tuple.

set() function

With the set function, we can grab the unique characters from within a string, or any other iterable type (eg. list or tuple).

>>> yellowFruit = set('banana') 
>>> yellowFruit 
{'b', 'a', 'n'}
>>> yellowFruit = set([1,2,3,3,2,1]) 
{1, 2, 3}

Curly braces {}

If we create sets using curly braces, then we can be more specific as to which strings we want in our set.

>>> banana = {'ba', 'an', 'na'}
>>> banana
{'ba', 'an', 'na'}

Frozen set

In a regular set, the elements can be modified with methods add() and remove(). Due to this, we cannot use a hash values within regular sets, causing a slight decrease in efficiency.

Instead, we may use frozen sets to achieve hashability. These are immutable, but are slightly more efficient. To call a frozen set, use the frozenset function to create one.

>>> fs = frozenset([1,2,3,3,2,1])
>>> fs
frozenset({1, 2, 3})
>>> fs.add(10)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'

Set functions

You may compare sets as they are mathematically.

x in s
Does x exist in s?
x not in s
Does x not exist in s?
Union. Returns set with elements from both s and t.
s & t
Intersection. Returns set of elements common to s and t.
s - t
Returns a new set with elements in s but not in t.
Copies a new set with a shallow copy of s.
Disjoint set. Boolean returns whether set s and c have anything in common.
s <= t, s < t
Subset. Checks if s is a subset of t.
s >= t, s > t
Check if s is a superset of t.

Here are some samples of the functions above.

>>> s = set('banana')
{'b', 'a', 'n'}
>>> print(s)
>>> t = set('pineapple')
{'a', 'i', 'e', 'n', 'l', 'p'}
>>> print(t)
>>> len(s)
>>> s.union(t)
{'a', 'i', 'e', 'b', 'n', 'l', 'p'}
>>> s.intersection(t)
{'a', 'n'}
>>> s.difference(t)

Set Manipulation

s |= t
Update s by adding elements in t.
s &= t
Intersection updating.
Updates s to keep elements that are found in both s and t.
s -= t
Different updating.
Updates s to keep only the elements that are in s but not in t.
s ^= t
Symmetric difference.
Updates s to keep only the elements that are either s or t.
Adds item to s.
Remove item from s.
Removes item from s.

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Python Programming

Learn to be a Pythonista! Try Python

This book is designed to be used as the primary textbook in a college-level first course in computing. It takes a fairly traditional approach, emphasizing problem solving, design, and programming as the core skills of computer science. However, these ideas are illustrated using a non-traditional language, namely Python.

$ Check price
45.9945.99Amazon 4.5 logo(211+ reviews)

More Python resources