Named tuple

2 snippets across 2 stacks - Python, TypeScript

PYPython

Named Tuples

PY · Tuples & Sets
Syntax
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
Example
from collections import namedtuple

Color = namedtuple("Color", ["red", "green", "blue"])
sky = Color(135, 206, 235)
print(sky.red, sky.blue)
print(sky._asdict())
Output
135 235
{'red': 135, 'green': 206, 'blue': 235}

Note Named tuples give readable field access while staying immutable. For mutable fields or defaults, consider dataclasses instead.

TSTypeScript

Arrays & Tuples

TS · Basic Types
Syntax
let arr: Type[] = [...];
let arr: Array<Type> = [...];
let tup: [TypeA, TypeB] = [a, b];
Example
let scores: number[] = [95, 87, 72];
let names: Array<string> = ["Alice", "Bob"];

// Tuple - fixed length, positional types
let userRecord: [string, number, boolean] = ["alice", 30, true];

// Named tuple elements (TS 4.0+)
let range: [start: number, end: number] = [0, 100];
Output
// userRecord[0] is string, userRecord[1] is number, userRecord[2] is boolean

Note Type[] and Array<Type> are identical. Tuples enforce length and per-position types at compile time, but at runtime they are just arrays - push() can still add elements unless you mark the tuple as readonly.

Frequently asked questions

How does Python handle named tuple?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Named Tuples" snippet in Python uses `from collections import namedtuple`.
Which code does the Python example use?
The "Named Tuples" snippet uses `from collections import namedtuple`, from the Tuples & Sets section of the Python cheat sheet.
Which stacks cover "named tuple" on this page?
Python, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Named Tuples": Named tuples give readable field access while staying immutable. For mutable fields or defaults, consider dataclasses instead.