python sets data-structures

Sets in Python

Learning objectives

By the end of this pill you will be able to:

  • create and initialise sets (set);
  • build a set from a list, removing duplicates;
  • add and remove elements from a set;
  • use the main set operations (union, intersection, difference);
  • clearly distinguish a set from a list, particularly regarding ordering.

What is a set

A set in Python represents a mathematical set: an unordered collection of unique elements. It is defined with curly braces { } or with the set() function.

fruits = {"apple", "banana", "pear"}
empty  = set()             # empty set

Note: You cannot create an empty set with {}: in that case Python creates a dict.

Creating a set from a list

We often want to remove duplicates from a list: just convert it to a set. This is a quick way to get unique elements.

lst = [1, 2, 2, 3, 3, 3, 4]
unique = set(lst)
print(unique)   # {1, 2, 3, 4}

Note: Converting back to a list with list(set(...)) gives a list without duplicates, but the original order may not be preserved.

Sets and element order

Sets in Python are unordered: they do not maintain the insertion sequence like lists do. When you print or iterate over a set, the order of elements can vary between runs.

s = {"a", "b", "c", "d"}
print(s)     # order may vary, e.g. {'a', 'c', 'b', 'd'}
for x in s:
    print(x) # does not follow insertion order

Note: If you need an ordered collection, you can convert the set to a list and sort it:

s = {3, 1, 4, 2}
ordered = sorted(s)
print(ordered)   # [1, 2, 3, 4]

Adding and removing elements

add() to insert

numbers = {1, 2, 3}
numbers.add(4)
print(numbers)     # {1, 2, 3, 4}

remove() and discard() to delete

numbers = {1, 2, 3}
numbers.remove(2)     # removes 2
print(numbers)        # {1, 3}

numbers.discard(99)   # no error if element not present

pop() and clear()

s = {"a", "b", "c"}
print(s.pop())   # removes and returns a random element
s.clear()        # empties the set
print(s)         # set()

Set operations

Union

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)             # {1, 2, 3, 4, 5}
print(a.union(b))        # same result

Intersection

print(a & b)             # {3}
print(a.intersection(b))

Difference and symmetric difference

print(a - b)             # {1, 2}
print(b - a)             # {4, 5}
print(a ^ b)             # {1, 2, 4, 5}  (exclusive elements)

Iterating over a set

Like lists, sets can be iterated with a loop, but order is not guaranteed.

colours = {"red", "green", "blue"}
for c in colours:
    print(c)

Differences between set and list

  • Order: lists maintain insertion order; sets do not.
  • Duplicates: lists can contain repeated elements; sets automatically eliminate duplicates.
  • Operations: sets have set operations (union, intersection, …); lists do not.
  • Indexing: in lists you can access by index (list[0]); in sets you cannot.
lst = [1, 2, 2, 3]
s   = {1, 2, 2, 3}
print(lst)  # [1, 2, 2, 3]
print(s)    # {1, 2, 3}

In brief: use a list when you need order and duplicates; use a set when you need unique elements and set operations.