Thursday, January 16, 2020

Named Tuple in Python

In this post we’ll see what are named tuples in Python and how to use them.

In a tuple you can store arbitrary elements and access them using index. Now, consider the scenario where tuple is storing a lots of fields, remembering field ordering and accessing them using index becomes quite a task and it is also less readable. In such scenarios named tuple is handy.


Python named tuple

A named tuple is a custom tuple data type which provides ability to refer the items in the tuple by both item names as well as by index position.

A named tuple is similar to plain tuple providing the same performance and the immutability feature.

Creating named tuple

To create a named tuple you need to import named tuple from the Collections module.

from collections import namedtuple

Here namedtuple() is a factory function that returns a tuple class.

Syntax for creating named tuple

namedtuple(typename, field_names)

Here typename is the name of the new tuple subclass which is used to create tuple-like objects.

field_names represent fields which are stored in the named tuple. They can be provied as a sequence of strings like ['field1', 'field2'] or as a single string with each fieldname separated by whitespace and/or commas, for example 'field1 field2' or 'field1', 'field2'.

For example-

Employee = namedtuple('Employee',['id', 'name','age'])

Here named tuple Employee is created which can store field id, name and age.

You can also provide fieldnames as a single string separated by white space.

Employee = namedtuple('Employee', 'id name age')

Python named tuple example

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', '28')
e2 = Employee('124', 'Lisa', '31')

# Access using index
print('Employee Age', e1[2])

# Access using field name
print('Employee Name', e2.name)

#iterating
for emp in [e1, e2]:
    print('Employee Id', emp.id, 'Employee Name', emp.name, 'Employee Age', emp.age)

Output

Employee Age 28
Employee Name Lisa
Employee Id 123 Employee Name Joe Employee Age 28
Employee Id 124 Employee Name Lisa Employee Age 31

Use cases for named tuple usage

1. You have a list in Python that stores objects of same type. Rather than creating a class with the fields and then creating objects of that class and storing them in the list you can create a named tuple which is much easier to create.

Here is the same example as above but uses list to store named tuples.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')
#list
employees = []
# storing named tuples
employees.append(Employee('123', 'Joe', '28'))
employees.append(Employee('124', 'Lisa', '31'))

# Access using index
print('Employee Age', employees[0][2])

# Access using field name
print('Employee Name', employees[0].name)

# iterate list
for emp in employees:
    print('Employee Id', emp.id, 'Employee Name', emp.name, 'Employee Age', emp.age)

Output

Employee Age 28
Employee Name Joe
Employee Id 123 Employee Name Joe Employee Age 28
Employee Id 124 Employee Name Lisa Employee Age 31

2. You have a CSV file with a record structure. You can create a similar record structure using named tuple and read records into named tuple directly.

import csv
from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

for emp in map(Employee._make, csv.reader(open("F:\\NETJS\\employee.csv", "r"))):
    print(emp.id, emp.name, emp.age)

Here note that _make method of the named tuple is used which is a class method that makes a new instance from an existing sequence or iterable.

Methods in named tuple

In addition to the methods inherited from tuples, named tuples support three additional methods.

1. _make(iterable)- Class method that makes a new instance from an existing sequence or iterable. We have already seen an example of this method.

2. _asdict()- Return a new dict which maps field names to their corresponding values.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', '28')
print(e1._asdict())

Output

OrderedDict([('id', '123'), ('name', 'Joe'), ('age', '28')])

3. _replace(**kwargs)- Return a new instance of the named tuple replacing specified fields with new values.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', 28)
print(e1)
print(e1._replace(age=30))

Output

Employee(id='123', name='Joe', age=28)
Employee(id='123', name='Joe', age=30)

That's all for this topic Named Tuple in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Concatenating Lists in Python
  2. Class And Object in Python
  3. Passing Object of The Class as Parameter in Python
  4. Magic Methods in Python With Examples
  5. Abstraction in Python

You may also like-

  1. Ternary Operator in Python
  2. Check if String Present in Another String in Python
  3. User-defined Exceptions in Python
  4. Convert String to int in Python
  5. ReentrantLock in Java Concurrency
  6. How HashMap Works Internally in Java
  7. Generics in Java
  8. Array in Java With Examples