ReviseAlgo Logo

Tuples

Named Tuples

Creating tuples with named fields

Interview: Shows knowledge of Python standard library and clean data modeling

Last Updated: June 12, 2026 8 min read

Named tuples provide a way to create lightweight, immutable record types with named fields. They combine the memory efficiency of tuples with the readability of objects. Available via collections.namedtuple (functional style) and typing.NamedTuple (class-based style with type hints).

collections.namedtuple

  • Create: Point = namedtuple('Point', ['x', 'y'])
  • Access: By name (p.x) or index (p[0])
  • Still a tuple: Supports all tuple operations (iteration, unpacking, len, etc.)
  • Immutable: Can't change fields after creation
  • Utility methods: _asdict(), _replace(), _make(), _fields

typing.NamedTuple (Python 3.6+)

  • Class-based syntax with type hints — more modern and IDE-friendly
  • Supports default values and docstrings
  • Same memory footprint as collections.namedtuple
  • Preferred in new code for better type checking and IDE support

When to Use Named Tuples

  • Simple immutable records (coordinates, RGB colors, database rows)
  • When you want attribute access without the overhead of classes
  • Return types for functions that return structured data
  • Upgrade to dataclasses when you need mutability, inheritance, or methods

namedtuple vs dataclass

Use namedtuple for simple immutable records. Use @dataclass when you need mutability, default factories, custom methods, or inheritance. Dataclasses are the modern default for most record-like types.

Use Cases

Lightweight immutable record types (coordinates, config entries)

Function return types for structured data

Replacing dictionaries for simple fixed data

Database row representations

Common Mistakes

Using _replace() without capturing the return value (it returns a NEW tuple, doesn't modify in place)

Not knowing that namedtuple fields starting with _ are reserved for internal use

Using namedtuple when you need mutability (use dataclass instead)

Forgetting that namedtuple subclasses tuple, so isinstance checks pass for both