Skip to content
CodeNest

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.

Python
Output
3 7
3
Cannot change a tuple: 'tuple' object does not support item assignment
— expected output; press Run to execute it yourself

Unpacking

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.

Python
Output
3 7
2 1
3 91
— expected output; press Run to execute it yourself

Sets

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.

Python
Output
3 unique visitors
True
['ada', 'bob', 'cleo']
— expected output; press Run to execute it yourself

Set maths

Sets support the operations you know from Venn diagrams, which makes "who is in both lists?" questions trivial.

Python
Output
['ada', 'bob', 'cleo', 'dan']
['bob']
['ada', 'cleo']
['ada', 'cleo', 'dan']
— expected output; press Run to execute it yourself

Exercise

Write dedupe(items) that returns a sorted list of the unique values in items.

Python
Output

Press Run to execute this code.

Check your understanding

0/2 answered
  1. 1.Which statement about tuples is true?
  2. 2.What is len(set([1, 2, 2, 3, 3, 3]))?