Introduction

Tuples are a data type in Python that allow for the storage of multiple elements in a single variable. Named tuples, on the other hand, are an extension of the tuple data type that provide additional functionality such as named elements and the ability to access those elements using either an index or a name. This tutorial will explore the benefits of using named tuples in Python, and will demonstrate how to create, modify, and access named tuples in your Python code.

Table of Contents :

  • Introduction
  • Creating named tuple classes in Python
  • Instantiating named tuples in Python
  • Accessing data of a named tuple
  • Using the rename argument of the namedtuple function
  • More named tuples functions in Python

Introduction :

  • Named tuples are a way to create a class without defining a separate class explicitly.
  • They allow you to define a new object type with named fields, making your code more expressive and self-documenting.

Creating named tuple classes in Python :

  • To create a named tuple, you need to import the  namedtuple  function from the  collections  module 
  • then call it with a name and a list of field names.
  • Code Sample : 

from collections import namedtuple
Person = namedtuple("Person", ["name", "age", "gender"])


Instantiating named tuples in Python :

  • You can create an instance of a named tuple by calling the name of the tuple class and passing in the values for each field.
  • Code Sample : 

person1 = Person("Alice", 25, "Female")
person2 = Person("Bob", 31, "Male")


Accessing data of a named tuple :

  • You can access the fields of a named tuple using the dot notation.
  • Code Sample : 

print(person1.name)
print(person2.age)


Using the rename argument of the namedtuple function :

  • You can specify the rename argument of the  namedtuple  function to avoid name conflicts and inconsistencies.
  • Code Sample : 

Person = namedtuple("Person", ["name", "age", "gender"], rename=True)
person1 = Person("Alice", 25, "Female")
person2 = Person("Bob", 31, "Male")
person3 = Person("Carl", 22, gender="Male")


More named tuples functions  in Python :

  • Named tuples provide additional Python functions like 
    • _make, 
    •  _asdict 
    •  _fields 
    •  _replace , etc., 
  • These functions can be used to manipulate and create new named tuples.
  • Code Sample : 

data = [("Alice", 25, "Female"), ("Bob", 31, "Male"), ("Carl", 22, "Male")]
people = [Person._make(person_data) for person_data in data]
person_dict = person1._asdict()
fields = Person._fields
person1_renamed = person1._replace(name="Alicia")



Prev. Tutorial : Property decorators

Next Tutorial : Context Managers