Defining a Set in Python
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: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.
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.
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.
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.
Become a Member to join the conversation.