Sub topic 2
Creating sets
This chapter assumes you know basic Python syntax, the difference between mutable and immutable objects, and how lists, tuples and dictionaries work. You should also be comfortable with for loops and the in operator. Here you will learn the three ways to build a set, and which one to use in each situation.
Set literals
A set literal is a comma-separated list of values inside curly braces. Python drops duplicates as it builds the set.
fruits = {"apple", "banana", "apple"}
print(len(fruits)) # 2, duplicates are droppedCurly braces are also used for dictionaries. Python tells them apart by the contents. {1, 2} has bare values, so it is a set. {1: "a"} has key-value pairs, so it is a dict.
The set() constructor
set() takes any iterable and builds a set from its items. An iterable is any object you can loop over, such as a list, a tuple, a string, a range or a generator.
letters = set("hello")
print(len(letters)) # 4, because 'l' appears twice
from_list = set([3, 1, 3, 2])
print(sorted(from_list)) # [1, 2, 3]
from_range = set(range(5))
print(sorted(from_range)) # [0, 1, 2, 3, 4]The constructor and the literal can give different results for the same text. set("hello") loops over the string and produces one element per character. {"hello"} produces a set with one element, the whole string.
print(sorted(set("hi"))) # ['h', 'i']
print({"hi"}) # {'hi'}The constructor accepts exactly one iterable, or none. Passing a non-iterable such as set(5) raises TypeError: 'int' object is not iterable.
When you pass a dictionary, you get its keys, because iterating a dict yields keys.
prices = {"tea": 3, "milk": 2}
print(sorted(set(prices))) # ['milk', 'tea']The empty set
The literal {} creates an empty dictionary, not an empty set. Use set() for an empty set.
empty = set() # {} would create an empty dict
print(type({})) # <class 'dict'>
print(type(empty)) # <class 'set'>Python prints an empty set as set(), so the output matches the way you create it.
Choosing a creation method
The fourth option, the set comprehension, is covered in a later chapter. Here is a short preview.
squares = {n * n for n in range(-3, 4)}
print(sorted(squares)) # [0, 1, 4, 9]Elements must be hashable
Every element you put in a set must be hashable. A hashable object has a fixed hash value for its lifetime, so Python can use it to place the element in the set. Immutable built-in types such as numbers, strings and tuples of hashable items qualify. Lists, dicts and sets do not.
points = {(1, 2), (3, 4)} # tuples are hashable
print((1, 2) in points) # True
try:
bad = {[1, 2], [3, 4]} # lists are not hashable
except TypeError as e:
print(e) # unhashable type: 'list'The error appears when the set is built, not later. The same applies to set([[1, 2]]). If you need a collection inside a set, convert the list to a tuple first.
Order and equality
A set does not keep a meaningful order, so print(fruits) may show elements in any order. Two sets are equal when they hold the same elements, whatever order you wrote them in. When you need stable output, as in tests or logs, wrap the set in sorted().
print({1, 2, 3} == {3, 2, 1}) # True
print(sorted({"b", "a"})) # ['a', 'b']Exercise
What does len({}) , len(set()), len(set("aab")) evaluate to, and what type is {}?
Show answer
It evaluates to (0, 0, 2). {} is an empty dict, set() is an empty set, and set("aab") has two elements, 'a' and 'b'. The type of {} is dict.
Exercise
Why does {["x"], ["y"]} raise a TypeError, and how would you fix it?
Show answer
Lists are mutable and therefore unhashable, so they cannot be set elements. Use tuples instead: {("x",), ("y",)}.