Sets
Code sample link: https://replit.com/@jjoco/python-sets
Sets are unordered (ie does not remember the insertion order) and unindexed (ie cannot read or write an element via an index) records of values. Python sets can be utilized like mathematical sets, as operations between sets are similar to that of mathematical sets (eg. intersections, unions, etc.). Each item in a set is unique, and fortunately, one can iterate through a set and can add items into it.
Why use sets
Sets in Python are highly optimized for reading and writing speed. When you check if a list contains some certain value, Python, at worst, would need to search through the entire list. On other hand, Python, at worst, would need to use a lookup table to figure out if an item exists in the set. To be more technical, time complexities for reading and writing values in a set is O(1)
.
Creating a set
To create an empty set, you can use the set()
function, or use curly braces like dictionaries. Keep in mind that Python will interpret empty curly braces as a dictionary; however, populated curly braces with items (that are not key-value pairs) will be interpreted as sets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Checking if a set contains an element
Use keyword in
to check to see if a value exists in a set:
1 2 3 4 5 6 7 8 |
|
Pushing an element into a set
Use the .add(elem)
method to add an item into a set:
1 2 3 4 5 6 |
|
Getting the length of a set
You can use len
to get the number elements in a set (ie. its length) .
1 |
|
my_set = {'set', 'world', 'hello'}
, then len(my_set)
would be 3
.
Iterating
You can interate through a set like any other collection:
1 2 3 4 5 6 7 8 9 |
|
Clear set
Use .clear()
to remove all items in the set
1 2 3 4 5 6 |
|
Set operations
Like I alluded to before, set operations can be used between set operands. The following subsections will use the following sets in their examples:
1 2 3 |
|
Union
Given sets A
and B
, use |
or A.union(B)
to get the union of the two sets (ie a set of all distinct elements common or not common in the two sets)
1 2 3 |
|
Intersection
Given sets A
and B
, use &
or A.intersection(B)
to get the intersection of the two sets (ie a set of all distincts elements common in the two sets)
1 2 3 |
|
Difference
Given sets A
and B
, use -
or A.difference(B)
to get the union of the two sets (ie a set of all elements in A
, but not in B
).
1 2 3 |
|
Is Subset
Given sets A
and B
, use <=
or A.issubset(B)
to check if A
is a subset of B
(ie. all elements in A
are contained in B
)
1 2 3 |
|
Is Superset
Given sets A
and B
, use >=
or A.issuperset(B)
to check if A
is a superset of B
(ie. A
contains all elements in B
)
1 2 3 |
|