Sets and membership

Lesson 42 of 54 · Python Foundations

A set holds distinct, hashable values without a guaranteed iteration order. It is useful when the question is whether a value exists, rather than where it occurs or how many times it occurs.

colors = {"blue", "red", "blue"}
print(len(colors))
print("blue" in colors)
print("green" not in colors)
2
True
True

The repeated "blue" contributes one member. An empty set is set(); {} is an empty dictionary. Set members must be hashable, like dictionary keys: a list cannot be a member, but a tuple of strings can. Equal values such as 1 and True occupy one set entry.

tags = set()
tags.add("python")
tags.add("python")
tags.add("data")
print(len(tags))
tags.discard("missing")
tags.remove("data")
print("data" in tags)
2
False

Adding an existing member changes nothing. remove raises KeyError when a member is absent; discard leaves the set unchanged. A set is mutable, but it is not a sequence and does not support indexing. Iteration is possible with for, though its order is not guaranteed. Use sorted(tags) when displaying comparable values in a predictable order.