Learn Python
>>> data_structures.namedtuple
Named Tuples in Python
#concept
A namedtuple, from the collections module, is a tuple where each position also has a name — combining a tuple's lightweight immutability with a class's readable, dot-accessed fields. It's a quick way to create a small, clear data structure without writing a full class.
#how it works
1
Import namedtuple
From the collections module, part of the standard library.
2
Define a new type
namedtuple("TypeName", ["field1", "field2", ...]) creates the type itself.
3
Create instances
Call it like a function, with positional or keyword arguments.
4
Access fields by name or position
point.x and point[0] both work, referring to the same value.
5
Still immutable
Like a regular tuple, a namedtuple cannot be changed once created.
#example
from collections import namedtuple Point = namedtuple("Point", ["x", "y"])p = Point(3, 4) print(p.x, p.y)print(p[0], p[1])print(p)Output
3 4
3 4
Point(x=3, y=4)
1namedtuple("Point", ["x", "y"]) creates a new tuple-like type called Point with two named fields.
2Point(3, 4) creates an instance, filling x and y in order.
3p.x and p.y access fields by name, which is far more readable than remembering that position 0 means x.
4p[0] and p[1] still work too, since a namedtuple is still a genuine tuple underneath.
5Printing p shows a clear, labeled representation rather than just (3, 4).
#use cases
Returning multiple named values from a function without writing a full class
Representing simple records, like a database row or a CSV line, with readable field access
Replacing 'magic number' tuple indexing (item[2]) with a clear field name (item.price)
A lightweight step up from a plain tuple when the meaning of each position matters
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.