Sub topic 1
What a Set Is
Prerequisites
Assume you know basic Python syntax, variables, lists, tuples, dictionaries, for loops, and the in operator. You should also know that mutable objects can change, while immutable objects cannot.
What a Set Is
A set is a mutable collection of unique, unordered elements. “Unique” means duplicates are stored only once. “Unordered” means a set does not preserve a position-based order that you can rely on.
fruits = {"apple", "banana", "apple"}
print(fruits)
print(len(fruits)) # 2The printed order can vary. Use a list when order or indexing matters.
Creating Sets
Use braces for a nonempty set. Use set() for an empty set because {} creates an empty dictionary.
numbers = {1, 2, 3}
empty = set()
from_text = set("hello")
print(sorted(from_text)) # ['e', 'h', 'l', 'o']The set() constructor accepts an iterable, such as a string, list, or tuple. It removes repeated values.
Which Values Can Go in a Set
Set elements must be hashable. A hashable value has a stable hash value during its lifetime, so Python can locate it efficiently. Immutable built-in values such as integers, strings, and tuples containing hashable values are normally hashable.
Lists and dictionaries are mutable and therefore cannot be set elements.
valid = {1, "python", (2, 3)}
try:
invalid = {[1, 2]}
except TypeError as error:
print(error) # unhashable type: 'list'Membership Tests and Iteration
Use in and not in to test membership. Sets are usually a better choice than lists when you perform many membership tests.
allowed = {"read", "write"}
print("read" in allowed) # True
print("delete" not in allowed) # True
for permission in allowed:
print(permission)Iteration order is unspecified, so do not write logic that depends on the loop order. Use sorted(allowed) when the elements can be compared and you need stable display order.
Exercise
What happens when you create set([2, 2, 4]), and why can you not create a set containing [1, 2]?
Show answer
It becomes {2, 4} because sets remove duplicates. [1, 2] cannot be an element because lists are mutable and unhashable.