NamedTuple Basics
Create lightweight immutable records.
NamedTuple Basics is a free Python Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a NamedTuple?
A named tuple is a tuple whose positions also have names. You get the lightweight, immutable nature of a tuple plus readable attribute access. It is perfect for small records.
The Problem with Plain Tuples
Plain tuples are positional, so you must remember what each index means. Code like p[0] and p[1] is easy to get wrong.
point = (1, 2)
print(point[0]) # x?
print(point[1]) # y?Creating with namedtuple
The factory collections.namedtuple builds a new tuple subclass. Pass the type name and the field names.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p)Access by Name
Now you can read fields by name instead of by index, which makes code self-explanatory.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x)
print(p.y)Still a Tuple
A named tuple is still a real tuple, so indexing, unpacking, and iteration all work as usual.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p[0])
x, y = p
print(x, y)Immutability
Like all tuples, named tuples are immutable. Trying to assign a field raises AttributeError.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
try:
p.x = 99
except AttributeError as e:
print('Cannot modify:', e)Making a Modified Copy
Since you cannot mutate it, use the _replace() method to produce a new instance with some fields changed.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
q = p._replace(y=99)
print(p)
print(q)Converting to a Dict
The _asdict() method returns the fields as a dictionary, useful for serialization or logging.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p._asdict())Inspecting Fields
The _fields attribute lists the field names. It is handy for generic code that iterates over a record's fields.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
print(Point._fields)Default Values
Provide defaults with the defaults argument. Defaults apply to the rightmost fields, just like function parameter defaults.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y', 'z'], defaults=[0])
print(Point(1, 2))
print(Point(1, 2, 9))Returning Multiple Values
Named tuples shine as function return values. Instead of returning an anonymous tuple, return a named one so callers read fields by name.
from collections import namedtuple
Stats = namedtuple('Stats', ['minimum', 'maximum'])
def analyze(nums):
return Stats(min(nums), max(nums))
r = analyze([3, 1, 9, 4])
print(r.minimum, r.maximum)Quick Check
How do you create a modified copy of a named tuple instance?
Recap
You learned to create lightweight immutable records.
namedtupleadds field names to tuples.- Access fields by name or by index; unpacking still works.
- Use
_replace()for modified copies and_asdict()to convert. _fieldslists the names;defaultssets defaults.
Frequently asked questions
Is the “NamedTuple Basics” lesson free?
Yes — the full text of “NamedTuple Basics” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “NamedTuple Basics”?
Create lightweight immutable records. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “NamedTuple Basics” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Enum Class
- IntEnum and Flag
- NamedTuple Basics
- typing.NamedTuple