Tuples are immutable, ordered collections of objects. Because tuples cannot be modified after instantiation, CPython optimizes their memory allocation, making them ideal for representing fixed data structures, function return pairs, and dictionary keys.
flowchart LR
subgraph Memory Stack
t["point = (10, 20, 30)"]
end
subgraph Tuple Heap Allocation
p0["index 0 -> int(10)"]
p1["index 1 -> int(20)"]
p2["index 2 -> int(30)"]
end
t --> Tuple Heap Allocation
| Attribute | list |
tuple |
|---|---|---|
| Mutability | Mutable | Immutable |
| Memory Overhead | Higher (pre-allocates extra capacity) | Lower (exact memory allocation) |
| Dict Key Fit | No (Un-hashable) | Yes (if all elements are hashable) |
| Syntax | [1, 2, 3] |
(1, 2, 3) |
from typing import Tuple, NamedTuple
class DatabaseConfig(NamedTuple):
host: str
port: int
user: str
def get_server_status() -> Tuple[int, str, float]:
"""Return a tuple representing (status_code, status_message, latency_ms)."""
return (200, "OK", 14.2)
if __name__ == "__main__":
# Tuple Unpacking
code, msg, latency = get_server_status()
print(f"Status Code: {code} | Message: '{msg}' | Latency: {latency}ms")
# NamedTuple Usage for Readability
db_info = DatabaseConfig("localhost", 5432, "postgres")
print(f"Connecting to {db_info.host}:{db_info.port} as {db_info.user}")
# Single Element Tuple Trailing Comma Requirement
single_tuple = ("standalone",) # Trailing comma is required!
print(f"Single Element Tuple Type: {type(single_tuple).__name__}")
("val") evaluates as a parenthesized string "val". You must include a trailing comma ("val",) to instantiate a single-element tuple.(1, [2, 3])), the nested list can still be modified!NamedTuple or dataclass(frozen=True): When returning structured records from functions, use typing.NamedTuple for field-name accessibility.Write a function swap_values(a: Any, b: Any) -> Tuple[Any, Any] that uses tuple packing and unpacking to swap two variables in a single expression.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With