Lesson 3 ❮ Lesson List ❮ Top Page
❯ 3.2 Sets
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 7m 53s
☷ Interactive readings 5m
Similar to lists and tuples, sets are used to store multiple items in a single variable. It is written with curly brackets { }.
Just like in math, a set has no order and no index. Sets also cannot have two items with the same value.
To add items to a set, you can use the following methods:
add(item)
adds item to the set.
update(iterable)
adds items from iterable (can be a set, list, tuple, etc.) into the current set.
Removing elements in a set is very similar to that of a list:
remove(item)
removes item from a set.
pop()
removes the last item. Since sets are unordered, so you will not know what item that gets removed.
There are some methods that can be applied only to sets (cannot be used in tuples and lists):
difference(set)
returns a set containing the difference between two or more sets.
symmetric_difference(set)
returns a set with the symmetric differences of two sets.
intersection(set)
returns a set, that is the intersection of two other sets.
union(set)
returns a set containing the union of sets.
Since sets cannot have multiple occurrences of the same element, they are useful to remove duplicate values from a list/tuple and to perform operations like unions and intersections.
You can easily convert a list or tuple to a set using set() and you can check its length using len(), just like in list and tuple.
Items in a set cannot be accessed by referring to an index or a key.
You can apply a for loop to ask if a specified value is present in a set using the in operator. Delete Line 3 to resolve the error.