Skip to content

Python Foundations·Lesson 7 of 67·beginner

Sets and tuples

Two collections with sharp edges — sets for uniqueness and fast membership, tuples for values that must not change.


In this lesson · 12 min

  • →Use sets to deduplicate and to test membership quickly
  • →Apply set algebra — union, intersection, difference
  • →Use tuples for fixed records and multiple return values
  • →Choose the right collection for a job

You have met lists and dictionaries. Two more collections round out the set, each solving a problem the others handle badly.

Sets: unique, unordered

A set holds each value at most once and does not remember an order.

PythonPython not started

Membership is fast

Checking x in collection on a list scans every item. On a set it is effectively instant, however large the set.

PythonPython not started

Changing a set

PythonPython not started

Sets are unordered, so there is no indexing and no .sort(). Convert to a list when you need an order:

PythonPython not started

Set algebra

This is where sets stop being “a list without duplicates” and start being genuinely useful.

PythonPython not started

That last check — intersecting your train and test ids — is a real data-leakage test you should run on every dataset you split.

Tuples: fixed, ordered

A tuple is an ordered sequence like a list, but it cannot be changed after it is created.

PythonPython not started

Duplicates are fine — a tuple is a sequence, not a set:

PythonPython not started

Working around immutability

You do not modify a tuple; you build a new one.

PythonPython not started

Why tuples exist

Unpacking. Assign several names at once:

PythonPython not started

Multiple return values. A function returning a tuple looks like it returns several things:

PythonPython not started

Dictionary keys. Because a tuple cannot change, it can be hashed — so it can be a key. A list cannot.

PythonPython not started

Choosing between them

Need Use
An ordered collection you will change list
A fixed record, or several return values tuple
Uniqueness, or fast membership tests set
Lookup by a meaningful key dict

Try it yourself

Exercise 1

Print the number of document ids that appear in both splits, as overlap: N.

Your turnPython not started
Exercise 2

Unpack record into name, score and latency in one statement.

Your turnPython not started

Check yourself

Which of these can be used as a dictionary key?

Recap

  • Sets hold unique values, have no order, and test membership in constant time.
  • |, &, - and ^ give you union, intersection, difference and symmetric difference.
  • {} is an empty dict; use set() for an empty set.
  • Tuples are immutable sequences — ideal for fixed records, unpacking and dictionary keys.
  • Unpacking (a, b = pair) is how Python functions return more than one value.