liveBook · Manning

Named tuple

As explained in Python How-To

A named tuple is an immutable tuple-like data structure whose elements can be accessed by descriptive field names as well as by position.

Need a small model for a task’s title, description, and urgency? A named tuple holds those distinct values in an immutable, tuple-like object. Its field names make access clearer than positional indexing, without requiring a hand-written class. section 3.3 section 3.3.1 section 3.3.2

Create and read a task

from collections import namedtuple Task = namedtuple('Task', 'title desc urgency') task = Task('Laundry', 'Wash clothes', 3) print(task.title) print(task) # Output: # Laundry # Task(title='Laundry', desc='Wash clothes', urgency=3) The factory function creates the Task class; calling that class creates a task. Fields can also be supplied to namedtuple as a comma-separated string or a list of strings. Give the class a descriptive, uppercase-camel-case name. section 3.3.2

Choose a named tuple when the model mainly holds data for reading. A list permits changes; an ordinary tuple lacks descriptive field access; a dictionary exposes names as keys but requires key lookups. Keep the one-line class definition visible, such as near the top of its module. Because the resulting object is immutable, changing an urgency value requires a new object rather than assigning to the existing field. section 3.3.1 section 3.3.3 section 3.3.4

for task_text in task_data.split('\n'):            #1
    title, desc, urgency = task_text.split(',')    #2
    task_nt = Task(title, desc, int(urgency))
    print(f"--> {task_nt}")
 
# output the following lines
--> Task(title='Laundry', desc='Wash clothes', urgency=3)
--> Task(title='Homework', desc='Physics + Math', urgency=5)
--> Task(title='Museum', desc='Epyptian things', urgency=2)

A parsing loop splits each incoming task record, converts urgency to an integer, and constructs a Task. The displayed output shows the field names alongside their values. section 3.3.2

The same lightweight model can package latitude and longitude as one function return value. Remember that tuple behavior still matters: when serialized to JSON, a named tuple becomes an array, not an object keyed by its field names. section 6.2.5 section 9.3.6

How Python How-To covers it

How deep it goes
Works through creation, named-field access, and record parsing; raises updating an immutable instance as a challenge.
Examples
Uses task records with title, description, and urgency, plus latitude-and-longitude return values.
What it assumes
Assumes basic Python containers and string splitting, but does not require knowing how to define a custom class.
What you can do after
Build it from scratch with collections.namedtuple and use named fields to read parsed task records.
How it connects
Compares lists, tuples, dictionaries, and custom classes; connects named tuples to function return values and JSON serialization.

Also explained in

Compare how 3 books explain named tuple →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.