Datastructures - Sets
Sets in Python are equivalent to sets in Mathematics. They look similar to lists, however they have a much different use. Every element in a set must be unique. If an element is added to it when it already exists, then no new element will be added.
A set is an unordered collection of unique elements; any duplicates are automatically removed upon creation or insertion.
Sets are written with curly brackets {}
,
or the built in function set
.
Sets A through C make singular value sets, while D
makes a set of 3 elements. Similar to
the tuple
function, using the set
function
requires a comma in the special case of a single element in the set.
Unlike with lists or tuples, duplicates are automatically removed. Additionally, the order doesn't matter. In the third print statement we include a Boolean expression which we will learn in the Operators with Booleans lesson.
Once a set is created, we can continue adding elements to it or remove
elements from it. We use the methods add
and remove
respectively.
We can also cast a list or tuple to a set.
Sets can even have different datatypes, such as tuples. Though mixing datatypes like this is discouraged.
setMix = {(1,2), (3,), 4, "five"}
> {(1,2), (3), 4, "five"}We can test if something is in a set using the statement in
.
This will return a Boolean value True
or False
.
The latter two print statements show the difference between identifying an integer and a tuple.
Practice Question
Considering that sets only keep the unique values, what will the set below be reduced to?
{5,4,5,"ten", "ten"}
score: 0%