Today we’ll be talking about sets.
Here’s the video version of this article:
A set is an unordered collection of unique and immutable objects.
The Features of Sets
Here are the most important features of sets:
– Sets are mutable but they can’t contain mutable objects.
– We can define sets either using curly braces or using the built-in set function.
Defining Sets
Here’s how we define sets in curly braces:
>>> flowers = {"carnation", "daffodil", "rose", "pansy"}
>>> flowers
{'pansy', 'rose', 'carnation', 'daffodil'}
We can create sets out of sequences (strings, lists, tuples). This time let’s use the set(sequence) function. Any repeating elements in the sequence will not get into the set.
Here’s an example with a string:
>>> text = "hello"
>>> set(text)
{'l', 'o', 'h', 'e'}
Here’s an example with a list:
>>> colors = ["blue", "red", "yellow", "red", "orange", "black", "red", "blue"]
>>> set_of_colors = set(colors)
>>> set_of_colors
{'black', 'red', 'orange', 'yellow', 'blue'}
Finally an example with a tuple. This time we’re passing the literal directly as the argument of the method set:
>>> set((1, 4, 3, 5, 4, 2, 1 ,3 ,5, 2, 4, 1, 3))
{1, 2, 3, 4, 5}
The elements of a set must be immutable. If we try to make a set of mutable elements, like lists, we get an error:
>>> set(([2, 3], [4, 7, 8], [2, 3]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
If we need to create an empty set, we must use the set function:
>>> speaking_plants = set()
>>> type(speaking_plants)
<class 'set'>