← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Named Tuples Deep Dive

Topic: Data Structures

Advertisement

Introduction

Named tuples provide a way to create simple, immutable classes with named fields.

Basic Named Tuples

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y)           # 10, 20
print(p[0], p[1])         # 10, 20 (indexable)

With Defaults

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
Point.__new__.__defaults__ = (0, 0)  # Default values

p = Point()      # (0, 0)
p = Point(5)     # (5, 0)
p = Point(5, 3)  # (5, 3)

Methods

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])

# Convert to dictionary
p._asdict()  # {'x': 10, 'y': 20}

# Replace fields
p._replace(y=30)  # Point(x=10, y=30)

# Get field names
p._fields  # ('x', 'y')

# Make from iterable
Point._make([10, 20])  # Point(x=10, y=20)

Practice Problems

  1. Create named tuple for RGB color
  2. Use defaults in named tuple
  3. Convert list of tuples to named tuples
  4. Implement Point3D extending Point2D
  5. Use namedtuple in DataFrame

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →