10Sets

In this chapter, we cover the last object for data collection and that is set. Perhaps the best use for sets is that they cannot contain duplicate values so can be useful for storing unique values. They are also unordered and cannot be changed. Let's start by creating a set.

image

Here, we use the curly brackets as we did with a dictionary, however now we have no key value pairs and the content resembles that of a list of tuple. We are not constrained by having strings in it, let's add some integers to our set.

image

Here, we can see that the ordering of the set doesn't resemble what we put into it.

We can also create a set using the set builtin function as covered earlier.

image

We can create a set from a string but we need to be aware of how the curly brackets and set builtin work

image

What happens is that when you pass in a string using the curly brackets you retain the full string in but when passed in using set the string is split into the individual characters. Again note when the characters are split there is no ordering to them.

Next, we try and add a list to the set but we raise ...

Get The Python Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.