Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

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:

animals = set(["lion","tiger","elephant"])

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:

animals = set(["lion","tiger","elephant"])
print(animals)

Now you get:

{'elephant', 'tiger', 'lion'}

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.

mypetanimals = ["cat","cat","dog","rabbit"]
print(mypetanimals)
mypetanimalset = set(mypetanimals)
print(mypetanimalset)

This produces the output:

['cat', 'cat', 'dog', 'rabbit']
{'rabbit', 'cat', 'dog'}

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:

myset = set("elephant")
print(myset)

This gives:

{'t', 'n', 'h', 'a', 'l', 'e', 'p'}

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:

heroes = {'superman','spiderman','spiderman'}
print(heroes)

This gives:

{'spiderman', 'superman'}

You can also define an empty set:

emptyset = set()
print(emptyset)

This prints

set()

denoting an empty set.

Set union

Python Set Operations - Union

You can do basic set operations like union, intersection, etc. In Python, the set union is denoted by the “pipe” symbol, i.e., “|”.

farmanimals = {'cow','donkey','horse'}
homeanimals = {'dog','cat','elephant'}
print(farmanimals | homeanimals)

This prints:

{'donkey', 'dog', 'elephant', 'cow', 'cat', 'horse'}

Note that this operation doesn’t change the original sets. If you do:

farmanimals = {'cow','donkey','horse'}
homeanimals = {'dog','cat','elephant'}
print(farmanimals | homeanimals)
print(farmanimals)
print(homeanimals)

You get:

{'donkey', 'dog', 'cat', 'cow', 'elephant', 'horse'}
{'cow', 'horse', 'donkey'}
{'dog', 'elephant', 'cat'}

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:

farmanimals = {'cow','donkey','horse'}
homeanimals = {'dog','cat','elephant'}
print(farmanimals)
print(farmanimals.union(homeanimals))
print(farmanimals)

This outputs:

{'cow', 'donkey', 'horse'}
{'cow', 'dog', 'donkey', 'elephant', 'horse', 'cat'}
{'cow', 'donkey', 'horse'}

Note that the original sets are still unmodified.

You can also union multiple sets in a single statement:

farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken','goat'}
farmanimalsagain = {'mule','bison'}
print(farmanimals | morefarmanimals | farmanimalsagain)

This gives:

{'cow', 'bison', 'horse', 'chicken', 'mule', 'donkey', 'goat'}

Set intersection

Python Set Operations - Intersect

Just like the union operator, we have the set intersection operator denoted by &:

farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken', 'cow', 'donkey', 'goat'}
farmanimalsagain = {'mule', 'cow', 'bison'}
print(farmanimals & morefarmanimals)
print(farmanimals & morefarmanimals & farmanimalsagain)

This gives:

{'donkey', 'cow'}
{'cow'}

Similarly, you can use the intersection method to get the same effect:

farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken', 'cow', 'donkey', 'goat'}
farmanimalsagain = {'mule', 'cow', 'bison'}
print(farmanimals.intersection(morefarmanimals))
print(farmanimals.intersection(morefarmanimals,farmanimalsagain))

This yields the same result:

{'donkey', 'cow'}
{'cow'}

Set difference

Python Set Operations - Difference

Finally, the set difference operator works as expected:

farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken', 'cow', 'donkey', 'goat'}
farmanimalsagain = {'mule', 'cow', 'bison'}
print(farmanimals - morefarmanimals)

yields:

{'horse'}

Let us modify the last set and do one more difference:

farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken', 'cow', 'donkey', 'goat'}
farmanimalsagain = {'mule', 'cow', 'horse', 'bison'}
print(farmanimals - morefarmanimals - farmanimalsagain)

This yields the empty set as expected:

set()

Note that the difference operator is not symmetric. A-B is not the same as B-A (as it should not be).

Python Set Operations - Difference

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.

Python Set Operations - Symmetric Difference

The symmetric difference is computed as follows:

a = {'blue','red','green'}
b = {'red','yellow','orange'}
print (a ^ b)

This yields:

{'green', 'yellow', 'blue', 'orange'}

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.

a = {'blue','red','green'}
print(len(a))
print('blue' in a)
print('Blue' in a)
print('yellow' in a)

This gives:

3
True
False
False

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.

approvedcolors = {'blue','red','green'}
mycolor = {'red'}
print(mycolor.issubset(approvedcolors))

This gives:

True

If you flip the order:

approvedcolors = {'blue','red','green'}
mycolor = {'red'}
print(approvedcolors.issubset(mycolor))

you get:

False

But also note that:

approvedcolors = {'blue','red','green'}
mycolor = {'red'}
print(approvedcolors.issubset(approvedcolors))

gives:

True

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:

approvedcolors = {'blue','red','green'}
print(set().issubset(approvedcolors))

gives:

True

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.

Kodeclik sidebar newsletter

Join our mailing list

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

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.