Lesson 4 of 4
Work with collections of unique values: remove duplicates, test membership quickly, and compare groups with union, intersection and difference.
About 20 minutes
A set is a collection where every value appears at most once. Sets are written with curly braces, like dictionaries, but contain single values rather than key-value pairs. If you add a value that is already there, nothing changes.
Sets are unordered: they don't keep items in the order you added them, so you can't use indexes like s[0]. When you need the items in order, for example to print them, use sorted(), which returns a sorted list.
elements = {"Fe", "Cr", "Ni", "Fe", "Cr"}print(len(elements))print(sorted(elements))Converting a list to a set with set() throws away duplicates. This is the quickest way to find the distinct values in a dataset.
A batch of samples was labelled with its crystal structure. Which structures appear?
structures = ["FCC", "BCC", "FCC", "HCP", "BCC", "FCC"]distinct = set(structures)print(f"{len(structures)} samples, {len(distinct)} structures")print(sorted(distinct))add(x) puts one value into a set. remove(x) takes it out but raises a KeyError if it isn't there; discard(x) does the same without an error. Testing membership with in is very fast for sets, even when they are large.
alloying = {"Cr", "Ni"}alloying.add("Mo")alloying.add("Cr") # already present: no changealloying.discard("W") # not present: no errorprint(sorted(alloying))print("Mo" in alloying)Creating an empty set
{} creates an empty dictionary, not a set. Use set() for an empty set.Sets support the operations from mathematical set theory. They are a clear way to compare two groups: which items they share, which belong to only one, and which appear in either.
| Operator | Method | Result contains |
|---|---|---|
a | b | a.union(b) | Items in a, in b, or in both |
a & b | a.intersection(b) | Items in both a and b |
a - b | a.difference(b) | Items in a but not in b |
a ^ b | a.symmetric_difference(b) | Items in exactly one of a and b |
steel_304 = {"Fe", "Cr", "Ni", "C"}steel_316 = {"Fe", "Cr", "Ni", "Mo", "C"}print("Shared:", sorted(steel_304 & steel_316))print("Only in 316:", sorted(steel_316 - steel_304))print("All elements:", sorted(steel_304 | steel_316))The molybdenum in 316 stainless steel improves its resistance to corrosion, which the set difference picks out immediately.
| Structure | Ordered? | Changeable? | Duplicates? | Use it for |
|---|---|---|---|---|
List [...] | Yes | Yes | Yes | A sequence of similar values: measurements, samples |
Tuple (...) | Yes | No | Yes | A fixed record: coordinates, (symbol, mass) |
Dictionary {k: v} | Yes (insertion order) | Yes | Keys must be unique | Looking values up by name |
Set {...} | No | Yes | No | Unique values and comparing groups |
Choose an answer and press Check answer. You can retry as often as you like.