Tuples¶
Tuples are fixed-size, immutable collections that can hold different types.
Creating Tuples¶
Accessing Elements¶
Use dot syntax with numeric indices:
Destructuring¶
Extract all elements at once:
Ignore elements with _:
Rest Pattern¶
Collect remaining elements:
let t = (1, 2, 3, 4, 5)
let (first, *rest) = t
# first = 1, rest = (2, 3, 4, 5)
let (*init, last) = t
# init = (1, 2, 3, 4), last = 5
Operations¶
Concatenation¶
Spread¶
Slicing (Compile-Time)¶
let t = (10, 20, 30, 40, 50)
let middle = t[1:4] # (20, 30, 40)
let single = t[2:3] # 30 (element, not tuple)
Comparison¶
Membership (Homogeneous)¶
Builtins¶
For homogeneous tuples:
let nums = (10, 20, 5, 30, 15)
print(len(nums)) # 5
print(sum(nums)) # 80
print(min(nums)) # 5
print(max(nums)) # 30
Iteration (Homogeneous)¶
Note: Iteration only works when all elements have the same type.
Named Fields¶
Tuple elements are positional — a tuple type cannot name its fields. This does not parse:
When the fields deserve names, use a class:
class Point:
pub x: int
pub y: int
pub def __new__(self, x: int, y: int):
self.x = x
self.y = y
let p = Point(10, 20)
print(str(p.x)) # 10
print(str(p.y)) # 20
See Known Limitations.
Function Returns¶
Tuples are perfect for returning multiple values:
def divmod(a: int, b: int) -> tuple[int, int]:
return (a / b, a % b)
let (quotient, remainder) = divmod(17, 5)
print(quotient) # 3
print(remainder) # 2
Key Points¶
- Immutable: Elements cannot be changed after creation
- Fixed size: Length is known at compile time
- Heterogeneous: Can mix different types
- No single-element tuples: Use the value directly
- Compile-time indices: All indexing and slicing uses compile-time constants