Sets
In this lesson, we're going to look at sets. There are many collection types at our disposal and sets are one of them.
Sets are a mutable , unordered , unique , sequence of elements.
Sets are unique
Let's look at an example:
duplicate_numbers = [1, 1, 2, 2, 3, 3]
This list has duplicate numbers. What if we were to convert this into a set?
unique_numbers = set(duplicate_numbers)
print(unique_numbers)
>> {1, 2, 3}
By turning the list into a set, it removed all the duplicate numbers. Hence, a set being a collection of unique elements.
Sets are mutable
Sets are mutable. This means that we can change it. Sets have a built-in add
method which is similar to the append
method that we saw earlier for lists.
unique_numbers.add(4)
print(unique_numbers)
>> {1, 2, 3, 4}
It successfully added that number.
What distinguishes add
from append
is that if I try to add an already existing element to the set, add
will not add it.
unique_numbers.add(3)
print(unique_numbers)
>> {1, 2, 3, 4}
as you can see, the set did not change.
Sets are unordered
Sets are unordered, which means that we can't use indices to find elements in the set. The most effective way of doing so is by using the membership operator in
to check if an element exists within a set.
print(2 in unique_numbers)
>> True