Kodeclik Blog


Python Set Operations

Python sets are a very powerful data structure in the language. Python provides a very flexible set data structure and a wide range of set operations so you don’t have to implement your own functions.

Working with Sets in Python

Let us start with a simple example. Let us create a set of animals. Recall what a set means in mathematics. A set typically contains elements of the same type but in general the only requirement in Python is that a set not contain any duplicates. In other words, the elements of the set must be distinct.
Sets are also unordered. For instance the set of animals: {lion, tiger, elephant} is the same as the set {elephant, lion, tiger}. You might choose to follow some contention in listing the set elements (e.g., alphabetical order) but internally, and mathematically, the order does not matter.
Here is how you declare a set of animals in Python:
When you run this program, nothing happens. Well, it has created the set called animals containing 3 elements as you intended but you haven’t specified what to do with it. Let us try to print our newly created set:
Now you get:
Note two important aspects of what has happened. First, our set construction statement specified a list of strings and the set() constructor has taken the list and created a set out of the list. Second, the order in which the set is printed is different from the order you originally gave it. This is as intended. Recall that order has no meaning in set theory.
Let us try to create a set from a list that contains duplicates.
This produces the output:
Note that although you count 2 cats, 1 dog, and 1 rabbit among your pets, the set data structure only has one instance of a cat.

Forming sets from strings

There are many ways to form sets, not just from a list. For instance, you can provide a string as input, like:
This gives:
Notice what has happened. When you give a string as input (rather than a list), every character in the string has been made into an element of the set (again removing duplicates).
You can also direct define a set using curly brace notation:
This gives:
You can also define an empty set:
This prints
denoting an empty set.

Set union

You can do basic set operations like union, intersection, etc. In Python, the set union is denoted by the “pipe” symbol, i.e., “|”.
This prints:
Note that this operation doesn’t change the original sets. If you do:
You get:
A different way to do union is to do it with a union() method on one set with the other set as argument. Here is how that works:
This outputs:
Note that the original sets are still unmodified.
You can also union multiple sets in a single statement:
This gives:

Set intersection

Just like the union operator, we have the set intersection operator denoted by &:
This gives:
Similarly, you can use the intersection method to get the same effect:
This yields the same result:

Set difference

Finally, the set difference operator works as expected:
yields:
Let us modify the last set and do one more difference:
This yields the empty set as expected:
Note that the difference operator is not symmetric. A-B is not the same as B-A (as it should not be).

Symmetric difference

There is however such a thing as a symmetric difference operator which is simply doing the difference in both directions and union-ing the results.
The symmetric difference is computed as follows:
This yields:

Other set operations

Other operations involving sets involve finding the size of a set using the len() method and checking if an element is in a set using “in”. Here is how they work.
This gives:
Note that the first False is because ‘Blue’ is a different string than ‘blue’. The second False is because the element is not in the given set.

issubset()

You can check if a set is a subset of another set using the issubset() method.
This gives:
If you flip the order:
you get:
But also note that:
gives:
because a set is always a subset of itself. Also an empty set is a subset of any set. So the following piece of code:
gives:
There is an issuperset() method with similar semantics.
This blogpost has covered the basic concepts of Python sets, how to declare them, and work with them using set operations. There are many more Python set operations, such as Python set pop(). Also see our post on Python ordered sets.
If you liked learning about the set data structure and how to use it in Python, you will also like learning about the Python stack data structure. Also checkout our detailed blogpost on how to convert sets to tuples.
For more Python content, see our blogpost on Python's enumerate() capability and Python's XOR operator. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.