Tuples
What it means
Section titled βWhat it meansβA tuple ((1, 2, 3)) is an ordered sequence like a list, but immutable β once created, you canβt add, remove, or reassign its elements. Because theyβre immutable, tuples are hashable (when their contents are), so they can be used as dictionary keys or set members, unlike lists.
Examples
Section titled βExamplesβpoint = (3, 4)x, y = point # unpacking
coordinates = (10, 20, 30)print(coordinates[0]) # 10# coordinates[0] = 99 # TypeError: 'tuple' object does not support item assignment
# Common use: dict keys (tuples are hashable, lists aren't)distances = {(0, 0): 0, (1, 1): 1.41}
def min_max(numbers): return (min(numbers), max(numbers)) # returning multiple values as a tuple
low, high = min_max([4, 1, 9, 2]) # unpacked directlyCommon mistake
Section titled βCommon mistakeβForgetting the trailing comma when creating a single-element tuple β (5) is just the integer 5 in parentheses, not a tuple.
not_a_tuple = (5)print(type(not_a_tuple)) # <class 'int'>
actual_tuple = (5,) # the comma is what makes it a tupleprint(type(actual_tuple)) # <class 'tuple'>Quick practice
Section titled βQuick practiceβ-
What makes
(5,)a tuple but(5)just an integer?Answer
The trailing comma β parentheses alone are just grouping syntax; the comma is what actually creates a tuple. -
Why can tuples be used as dictionary keys but lists canβt?
Answer
Tuples are immutable and hashable (as long as their contents are); lists are mutable and therefore unhashable, so they're not allowed as dict keys. -
What does
x, y = (3, 4)do?Answer
Tuple unpacking β it assigns3toxand4toyin one statement.