Data Structures
Tuple
Read by index: O(1) · Create: O(n) for n elements · No add/remove after creation — the size is locked in forever.
The idea, in plain English
A tuple is like a sealed gift box with numbered slots. Slot 1 always holds the ribbon color, and slot 2 always holds the size. You can peek inside and read any slot at any time. But you can't swap out what's in slot 2 without unwrapping a whole new box. Once you make a tuple, it's locked. This is called immutable, meaning nothing inside it can change.
How it works
- 1Group a fixed set of values together, in a fixed order, sealed at the moment you create it.
- 2Read any value by its position (index), exactly like an array.
- 3Unpack the whole tuple into separate named variables in one line, if the language supports it.
- 4To 'change' anything, build and return a brand new tuple. The original one never changes.
When you'd use it
Use a tuple to return more than one value from a function, like a minimum and a maximum together. Also use it for a small fixed record, like a color as (r, g, b) or a point as (x, y), where each position's meaning is fixed and should never accidentally shift.
Common beginner mistakes
- Don't try to change a tuple in place, like tup[0] = 5. Real tuples reject this outright. Treat them as a stamped, read-only record, not a growable list.
- Don't reach for a tuple when you actually need a variable-length, growable collection. That job belongs to an array or list, not a tuple.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
x: 3
y: 4
Unpacked: 3,4
Min: 2
Max: 9
Blocked: yes
Still: 3Note: JavaScript has no native tuple type. So this lesson simulates one with Object.freeze on an array. This seals the array, so any write to it throws an error. Python's tuple is immutable by design. It needs no freezing.
See it in motion
Ready. A tuple is a small, fixed, ordered group of values — sealed the moment it's created.
Not sure this is the right topic? See the learning paths → or where this leads →