loop
Tuples and dictionaries

Module 4 · Tuples and dictionaries · Lesson 2 of 6

Tuples

A tuple is an ordered collection, just like a list — but immutable. You create one with commas (the parentheses are usually optional but make it clearer), and you read it by index exactly as you would a list. You just can't change it afterwards.

Run it yourselfruns in your browser · Python
main.py

Watch the one-item gotcha: (7,) is a tuple, but (7) is just the number 7 in brackets — it's the comma that makes a tuple, not the parentheses.

Tuples have one lovely trick called unpacking: assign a tuple to several variables at once and Python spreads the items out by position.

x, y = point
point =(3, 4)
x3
y4

The same trick powers the one-line swap a, b = b, a — pack on the right, unpack on the left.

This is why a function can “return several values” — it really returns one tuple, which you unpack on the way out. It's also the secret behind the elegant one-line swap a, b = b, a you saw with Fibonacci.

Run it yourselfruns in your browser · Python
main.py

Tuples are perfect when a group of values belongs together and shouldn't change — a coordinate, a date, a row of data. Next, a collection that looks things up by name instead of position.