Skip to content

Python Named Tuples | Infographic

  • by

Python Named Tuples are basically like normal tuples but you can access their value with .fildname. Named tuples are also immutable.

Named tuples are easy-to-create, lightweight object types. Named tuple instances can be referenced using object-like variable dereferencing or the standard tuple syntax.

  • Python Named Tuples

Python Named Tuples

A simple example code is named tuples.

import collections

Point2D = collections.namedtuple('Point2D', 'x y')

a = Point2D(3, -1)

print(a.x, a.y)

Point3D = collections.namedtuple('Point3D', ' '.join([*Point2D._fields, 'z']))

a = Point3D(3, -1, 2)


Python Named Tuples

Here’s an example of how to use named tuples:

from collections import namedtuple

# Define a named tuple type called 'Point' with fields 'x' and 'y'
Point = namedtuple('Point', ['x', 'y'])

# Create an instance of the named tuple
p = Point(x=1, y=2)

# Access elements using named attributes
print("x coordinate:", p.x)
print("y coordinate:", p.y)

Named tuples are immutable, meaning you can’t change the values once they’re created. However, you can create new named tuples with modified values by using the _replace() method:

# Create a new named tuple with a modified value
p2 = p._replace(x=5)

print("New x coordinate:", p2.x)

Named tuples are especially useful when dealing with data structures where you need to keep track of multiple attributes but don’t want the overhead of a full class definition. They provide a lightweight way to create structured data types.

Do comment if you have any doubts or suggestions on this Python basic topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading