You already know that we store dictionary keys in a single instance in the dictionary. Adding a new value to an existing key replaces the old value. This single instance storage property is often handy in cases where we want to store the keys themselves, not their values.
For example, suppose we want to store a list of cities your users have visited. We do not need to duplicate the record if they travel to the town twice. It saves storage space and makes it easier to find information. We may also need to find out which cities were visited by both Vasya and Masha and which were visited only by Masha (or only by Vasya).
In mathematics, sets are used to:
- To store a list of elements in certain sets
- To compare these sets with each other (abstract_data_type)
Python provides a data structure of the same name - set
. Thus, Python sets are unordered sequences of elements, where we represent each element only once in the set.
How to create sets and manipulate them
We can create a set using the corresponding literal:
s = {1, 2, 3, 2, 1}
s # {1, 2, 3}
type(s) # <class 'set'>
Developers write literals in curly brackets, just like dictionary literals. However, Python lists only the elements of the set inside the brackets separated by commas. Since the literal {}
is already occupied by dictionaries, we create an empty set by calling the set
function without arguments:
set() # {}
type(set()) # <class 'set'>
We can use the same function to create a set of elements from whatever iterable or iterator:
set('abracadabra') # {'c', 'd', 'a', 'r', 'b'}
set([1, 2, 3, 2, 1]) # {1, 2, 3}
Note that each unique element is represented exactly once in the set, even if there were repetitions in the source collection.
How to check the content of sets
We can check whether a value is an element of a set — some developers refer to the same state as to be part of a set or to belong to a set. To do so, we need to use the in
operator:
42 in set() # False
42 in set([42]) # True
'a' in set('abracadabra') # True
Later you'll learn how it works, but we can say that checking if something is in a set is very fast, much faster than checking if something is in a string, tuple, or list. Finding a key in the dictionary is just as speedy.
Dictionaries and sets use an identical mechanism for storing and searching for keys. It isn't so noticeable for small collections but becomes evident when you check a few dozen items multiple times.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.