> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python NamedTuple

A `NamedTuple` is a memory-efficient, shallowly immutable subclass of the built-in `tuple` data structure that allows elements to be accessed via explicit attribute names in addition to standard positional indices. It provides the structure of a class without the memory overhead of a per-instance `__dict__`.

Python provides two distinct implementations for creating named tuples: the dynamic factory function `collections.namedtuple` and the statically-typed class base `typing.NamedTuple`.

## 1. `collections.namedtuple`

This is a factory function that dynamically generates and returns a new tuple subclass. It accepts a typename and a sequence of field names (either as an iterable of strings or a single space/comma-delimited string).

```python theme={"dark"}
from collections import namedtuple


# Syntax: namedtuple(typename, field_names)
Record = namedtuple('Record', ['id', 'status', 'timestamp'])

# Alternatively: namedtuple('Record', 'id status timestamp')


# Instantiation
item = Record(id=101, status='active', timestamp=1630000000)


# Access via attribute or index
print(item.status)  # Output: 'active'
print(item[0])      # Output: 101
```

## 2. `typing.NamedTuple`

Introduced in Python 3.6, `typing.NamedTuple` utilizes class inheritance and variable annotations (PEP 526) to define fields. This is the modern standard, as it provides native support for static type checkers (like `mypy`) and IDE autocompletion.

Crucially, unlike `collections.namedtuple`, it allows developers to define custom methods, properties, and docstrings directly within the class body.

```python theme={"dark"}
from typing import NamedTuple

class TypedRecord(NamedTuple):
    """A record of an item's processing status."""
    id: int
    status: str
    timestamp: float
    
    # Default values are supported
    is_archived: bool = False

    # Custom methods and properties can be defined directly
    @property
    def is_active(self) -> bool:
        return self.status == 'active' and not self.is_archived


# Instantiation
item = TypedRecord(id=102, status='active', timestamp=1630000500.0)
print(item.is_active)  # Output: True
```

## Core Characteristics

* **Shallow Immutability:** Because it inherits from `tuple`, instances are shallowly immutable. Attempting to reassign an attribute directly raises an `AttributeError`. However, if a field contains a mutable object (like a `list` or `dict`), the contents of that object can still be modified in place.

```python theme={"dark"}
class Container(NamedTuple):
    tags: list[str]

c = Container(tags=['urgent'])
# c.tags = ['low']       # Raises AttributeError
c.tags.append('low')     # Allowed: modifies the list in place
```

* **Tuple Compatibility:** A `NamedTuple` is fully interoperable with standard tuples. It supports iteration, unpacking, and built-in functions like `len()`.

```python theme={"dark"}
# Unpacking behaves exactly like a standard tuple
record_id, status, ts, archived = item
```

* **Memory Efficiency:** Instances do not possess a `__dict__` attribute. Their memory footprint is identical to a standard `tuple`.

## Built-in Methods and Attributes

To prevent namespace collisions with user-defined field names, all built-in methods and properties specific to named tuples are prefixed with a single underscore `_`.

* **`_make(iterable)`**: A class method that instantiates a new named tuple from an existing iterable. It bypasses standard instantiation and does *not* apply default values; the iterable must have a length exactly matching the total number of defined fields.

```python theme={"dark"}
# Requires exactly 4 elements, matching all fields including 'is_archived'
data = [103, 'resolved', 1630001000.0, True]
item = TypedRecord._make(data)
```

* **`_asdict()`**: Returns a standard Python `dict` mapping the field names to their corresponding values.

```python theme={"dark"}
item_dict = item._asdict()
# {'id': 103, 'status': 'resolved', 'timestamp': 1630001000.0, 'is_archived': True}
```

* **`_replace(**kwargs)`**: Returns a new instance of the named tuple, replacing the specified fields with new values while leaving the others intact. This is the standard mechanism for "mutating" a named tuple.

```python theme={"dark"}
updated_item = item._replace(status='closed')
```

* **`_fields`**: A tuple of strings listing the field names defined on the class.

```python theme={"dark"}
print(TypedRecord._fields)
# ('id', 'status', 'timestamp', 'is_archived')
```

* **`_field_defaults`**: A dictionary mapping field names to their default values (if any were defined).

```python theme={"dark"}
print(TypedRecord._field_defaults)
# {'is_archived': False}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
