Python Sets

By

Learn how to use sets in Python, the unordered and mutable data structure, including intersection, union and difference operations, len() and the in operator.

~~~

A set is a Python data structure that stores an unordered collection of unique items.

We can say sets work like tuples, but they are not ordered, and they are mutable. Or we can say they work like dictionaries, but they don’t have keys.

They also have an immutable version, called frozenset.

You can create a set using this syntax:

names = {"Roger", "Syd"}

The “unique items” part matters. Duplicates disappear automatically:

names = {"Roger", "Syd", "Roger"}
print(names) # {'Syd', 'Roger'}

That’s the main reason to reach for a set: when you want to make sure each item appears once, or when you need fast membership checks.

Be careful when you need an empty set. {} creates an empty dictionary, not a set. Use the set() constructor instead:

empty = set()

Set operations

Sets work well when you think about them as mathematical sets.

You can intersect two sets:

set1 = {"Roger", "Syd"}
set2 = {"Roger"}

intersect = set1 & set2 #{'Roger'}

You can create a union of two sets:

set1 = {"Roger", "Syd"}
set2 = {"Luna"}

union = set1 | set2
#{'Syd', 'Luna', 'Roger'}

You can get the difference between two sets:

set1 = {"Roger", "Syd"}
set2 = {"Roger"}

difference = set1 - set2 #{'Syd'}

You can check if a set is a superset of another (and of course if a set is a subset of another):

set1 = {"Roger", "Syd"}
set2 = {"Roger"}

isSuperset = set1 > set2 # True

Notice that > checks for a strict superset, so a set is not a superset of itself. Use >= if equal sets should count too.

Adding and removing items

Since sets are mutable, you can add items with add():

names = {"Roger", "Syd"}
names.add("Luna")

You can remove an item with remove(), which raises a KeyError if the item is not in the set, or with discard(), which does nothing in that case:

names.remove("Luna")
names.discard("Vanille") # no error

Other common operations

You can count the items in a set with the len() global function:

names = {"Roger", "Syd"}
len(names) # 2

You can get a list from the items in a set by passing the set to the list() constructor:

names = {"Roger", "Syd"}
list(names) #['Syd', 'Roger']

Since sets are unordered, you can’t access items by index. names[0] raises a TypeError. If you need ordering, convert the set to a list first.

You can check if an item is contained into a set with the in operator:

print("Roger" in names) # True

This check is very fast on sets, even with many items, which makes them a better choice than lists when you do a lot of lookups.

Tagged: Python · All topics
~~~

Related posts about python: