Data StructuresLesson 10 of 1912 min
Tuples and Sets
Two more containers: one that cannot change, one that removes duplicates.
By the end you will be able to
- Create tuples and explain why immutability is useful
- Unpack a tuple into several variables
- Use sets for uniqueness and fast membership tests
Tuples
A tuple is an ordered collection like a list, but immutable — once built it cannot be changed. Write it with parentheses (or just commas).
Reach for a tuple when the group is a fixed record: a coordinate, an RGB colour, a row from a database.
3 7
3
Cannot change a tuple: 'tuple' object does not support item assignment
— expected output; press Run to execute it yourselfUnpacking
Assigning a tuple to several names at once splits it apart. This is used constantly — it is also how a function returns more than one value.
3 7
2 1
3 91
— expected output; press Run to execute it yourselfSets
A set is an unordered collection with no duplicates. Written with braces, or built with set().
Two things make sets worth knowing: removing duplicates is a one-liner, and testing membership is dramatically faster than scanning a list.
3 unique visitors
True
['ada', 'bob', 'cleo']
— expected output; press Run to execute it yourselfSet maths
Sets support the operations you know from Venn diagrams, which makes "who is in both lists?" questions trivial.
['ada', 'bob', 'cleo', 'dan']
['bob']
['ada', 'cleo']
['ada', 'cleo', 'dan']
— expected output; press Run to execute it yourselfExercise
Write dedupe(items) that returns a sorted list of the unique values in items.
Press Run to execute this code.