This lesson is from the Real Python video course by James Uejio.
Defining a Set in Python
00:00
There are two ways to define a set in Python. You can use the set()
function, which takes in a iterable and converts the iterable to a set.
00:09
So for example, we can pass the list ['foo', 'bar']
, which will convert that list into a set with those two elements. Notice how the order is not exactly the same as the list we passed in, because set are unordered, so it’ll just display in some random order.
00:25 Let’s see what happens when we pass in a dictionary. It will turn the keys of the dictionary into a set. We can also pass in a string, because that’s a iterable.
00:34 And that will split the string by characters and create a set from the resulting characters. And if there are any duplicate letters, it will only include those once because sets cannot contain duplicates.
00:45
It will also print out in a random order. For example, we could use the list()
function, which will turn a iterable into a list, and that will keep the order and the duplicates.
00:55
The second way we can define a set is by using the curly braces. So here, let’s create a set with two elements, I guess {'foo', 'bar'}
. And x
is the set {'foo', 'bar'}
.
01:07
If we want an empty set, we have to use the first method because, as we see, the second method like this is actually a dictionary and not a set. So we have to actually use set()
like this, which will be a set.
01:24
Let’s talk a little bit more about the empty set. That is a False
value, just like how empty lists and dictionaries are all False
values.
01:34
Sets are really cool because they can contain any hashable value, and the same set does not have to include the same type of value. So we can have a string, a Boolean, None
, and then a tuple—because, remember, tuples are immutable and by definition hashable—and that will work. Some other languages might not allow that, but Python does.
01:55
Let’s try to pass a not-hashable value and see what happens. Lists are not hashable, and this will error. And it actually says unhashable type: 'list'
. In the next section, you’ll learn different ways to operate on a set.
You must own this product to join the conversation.