Skip to content

Sets

Python has a built-in Set type - an unordered collection of distinct immutable objects. A set is a mutable object and so it can be altered. It offers a fast lookup of whether an element is in the set or not, and it comes equipped with standard set-theoretic operations: union, intersection, etc.

Unlike lists, where order matters, the order of the elements in a set does not matter. All that matters is the elements themselves. So in this sense, we can think of sets as unordered lists.

Sets are created using either using the function set() or braces { }. Duplicate items in a set are ignored.

Defining a Set

set([1,2,3])    # here we turn the list [1,2,3] into a set
Output:
{1,2,3}
set([1,2,3])==set([2,1,3])  # order doesn't matter in a set
Output:
True
set(range(1,101))   # using the range list to construct a set
Output:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20,
21, 22, 23, 24, 25,26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56,
57, 58, 59, 60,61, 62, 63, 64, 65, 66, 67, 68, 69, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80,81, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100}

If L is a list and S is a string, set(L) and set(S) produce the set of items/characters from the list/string.

print(set([1,2,3]))
print(set('hello world!'))
Output:
{1, 2, 3}
{'o', 'd', ' ', 'e', '!', 'h', 'l', 'r', 'w'}

We can construct sets by specifying conditions on the elements, much like we did with lists.

set(x for x in range(1,11) if x%2==0)
Output:
{2,4,6,8,10}
set(x for x in range(1,51) if x%3==0)   # integers divisible by 3
Output:
{3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48}

There is also a filter command for selecting elements satisfying some special condition. Here we select the even integers.

S=set(range(1,20))
set(filter(lambda x: x%2==0,S))
Output:
{2, 4, 6, 8, 10, 12, 14, 16, 18}

Set Operations

A number of operations and methods are available for set objects: add, remove, union, intersection, issubset, etc.

S1=set(x for x in range(1,15) if x%2==0)
S2=set(x for x in range(1,15) if x%3==0)
print(S1.union(S2))
print(S1.intersection(S2))
Output:
{2, 3, 4, 6, 8, 9, 10, 12, 14}
{12, 6}
small = {0, 1, 2, 3}; mid = {3, 4, 5, 6, 7}; big = {7, 8, 9}
big.add(10); small.remove(0)
print(small, big)
print(small.intersection(mid))
print(small.union(big))
Output:
{1, 2, 3} {8, 9, 10, 7}
{3}
{1, 2, 3, 7, 8, 9, 10}
d = {0,1}
print(d.issubset({0, 1, 2, 3}))
print(d <= {0, 1, 2, 3})
Output:
True
True

Using the set object to test whether a string is hexidecimal.

ex_char = "0123456789abcdef"
word = "12aac"
set(word) <= set(hex_char)
Output:
True
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
x.issubset(y)
Output:
True