In Python sets (type set) is the final Python Data Types are the final python data type we will be exploring.
Python sets are simply a collection of unordered unique elements. Let’s take our tuple from the last blog post and pass it into a set,
my_tup (1, 4, 2, 2, 3, 1, 1, 4, 4, 5, 6, 6, 3, 5, 6)
my_set = set(my_tup)
When we return my_set, we get an unordered collection of unique elements from the tuple.
my_set {1, 2, 3, 4, 5, 6}
We can create sets with curly brackets { }
as well. You do not need to cast a data type into a set, and you can also create a set on the fly
my_num = {1,1,2,2,34,5,6,7,8}
type(my_num)
<class 'set'>
my_num
{1, 2, 34, 5, 6, 7, 8}
Duplicate entries will be permanently removed when dealing with a set.
my_text = {'M','i','s','s','i','s','s','i','p','p','i'}
type(my_text)
<class 'set'>
my_text
{'s', 'i', 'p', 'M'}
In the above, we transformed a tuple into a set, and the duplicate entries are removed automatically. In addition to sets containing unique data, sets can not be indexed or sliced. Sets do have some pretty complex methods, which can be found here. Set methods and only a few will be demonstrated. We are going to create two new sets to show set methods:
s1 = {1,2,3,4}
s2 = {3,4,5,6}
.difference()
- This will compare two sets and only show the differences
- We will compare s1 to s2
s1.difference(s2)
{1, 2} - There is also
.difference_update()
that will update the method to the lefts1.difference_update(s2)
s1
{1, 2}
.isdisjoint()
- Will print False if they have any object in common.
s1.isdisjoint(s2)
False
- Will print False if they have any object in common.
.intersection()
- Returns the point at which both sets intersect
s1.intersection(s2)
{3, 4}
- Returns the point at which both sets intersect
.issuperset()
- Is a set a part of the set you are comparing it against
- Does s1 encompass your set, s2
s1.issuperset(s2)
False
issubet()
- is s1 a subset of s2, the object is the entirety of s1 in s2
s1.issubset(s2)
False
- is s1 a subset of s2, the object is the entirety of s1 in s2
.union()
- Join the two sets together
- It does not happen in place; we need to assign a variable.
s1.union(s2) {1, 2, 3, 4, 5, 6} union_set = s1.union(s2)
print(union_set)
{1, 2, 3, 4, 5, 6}