Kodeclik Blog
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.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
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.
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.
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.
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:
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:
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).
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 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.
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.
animals = set(["lion","tiger","elephant"])
animals = set(["lion","tiger","elephant"])
print(animals)
{'elephant', 'tiger', 'lion'}
mypetanimals = ["cat","cat","dog","rabbit"]
print(mypetanimals)
mypetanimalset = set(mypetanimals)
print(mypetanimalset)
['cat', 'cat', 'dog', 'rabbit']
{'rabbit', 'cat', 'dog'}
myset = set("elephant")
print(myset)
{'t', 'n', 'h', 'a', 'l', 'e', 'p'}
heroes = {'superman','spiderman','spiderman'}
print(heroes)
{'spiderman', 'superman'}
emptyset = set()
print(emptyset)
set()
farmanimals = {'cow','donkey','horse'}
homeanimals = {'dog','cat','elephant'}
print(farmanimals | homeanimals)
{'donkey', 'dog', 'elephant', 'cow', 'cat', 'horse'}
farmanimals = {'cow','donkey','horse'}
homeanimals = {'dog','cat','elephant'}
print(farmanimals | homeanimals)
print(farmanimals)
print(homeanimals)
{'donkey', 'dog', 'cat', 'cow', 'elephant', 'horse'}
{'cow', 'horse', 'donkey'}
{'dog', 'elephant', 'cat'}
farmanimals = {'cow','donkey','horse'}
homeanimals = {'dog','cat','elephant'}
print(farmanimals)
print(farmanimals.union(homeanimals))
print(farmanimals)
{'cow', 'donkey', 'horse'}
{'cow', 'dog', 'donkey', 'elephant', 'horse', 'cat'}
{'cow', 'donkey', 'horse'}
farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken','goat'}
farmanimalsagain = {'mule','bison'}
print(farmanimals | morefarmanimals | farmanimalsagain)
{'cow', 'bison', 'horse', 'chicken', 'mule', 'donkey', 'goat'}
farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken', 'cow', 'donkey', 'goat'}
farmanimalsagain = {'mule', 'cow', 'bison'}
print(farmanimals & morefarmanimals)
print(farmanimals & morefarmanimals & farmanimalsagain)
{'donkey', 'cow'}
{'cow'}
farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken', 'cow', 'donkey', 'goat'}
farmanimalsagain = {'mule', 'cow', 'bison'}
print(farmanimals.intersection(morefarmanimals))
print(farmanimals.intersection(morefarmanimals,farmanimalsagain))
{'donkey', 'cow'}
{'cow'}
farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken', 'cow', 'donkey', 'goat'}
farmanimalsagain = {'mule', 'cow', 'bison'}
print(farmanimals - morefarmanimals)
{'horse'}
farmanimals = {'cow','donkey','horse'}
morefarmanimals = {'chicken', 'cow', 'donkey', 'goat'}
farmanimalsagain = {'mule', 'cow', 'horse', 'bison'}
print(farmanimals - morefarmanimals - farmanimalsagain)
set()
a = {'blue','red','green'}
b = {'red','yellow','orange'}
print (a ^ b)
{'green', 'yellow', 'blue', 'orange'}
a = {'blue','red','green'}
print(len(a))
print('blue' in a)
print('Blue' in a)
print('yellow' in a)
3
True
False
False
approvedcolors = {'blue','red','green'}
mycolor = {'red'}
print(mycolor.issubset(approvedcolors))
True
approvedcolors = {'blue','red','green'}
mycolor = {'red'}
print(approvedcolors.issubset(mycolor))
False
approvedcolors = {'blue','red','green'}
mycolor = {'red'}
print(approvedcolors.issubset(approvedcolors))
True
approvedcolors = {'blue','red','green'}
print(set().issubset(approvedcolors))
True