Hello Pythonistas!
Today we will learn a simple tip that increases your code readability. That is use a namedtuple instead of a tuple/list
Let us consider the example student record with roll number, name, and age.
Using tuple
student = (1, “Guido Van Rossum”, 50)
roll_number = student[0]
name = student[1]
age = student[2]
Using namedtuple
from collections import namedtuple
Student = namedtuple('Student', ['roll_number', 'name', 'age'])
s = Student(1, 'Guido Van Rossum', '50')
print(s)
name = s.name
roll_number = s.roll_number
age = s.age
print(f"{name=}, {roll_number=}, {age=}")
## We can access namedtuple using index also
name = s[1]
roll_number = s[0]
age = s[2]
print(f"{name=}, {roll_number=}, {age=}")
## We can make namedtuple to dictionary using _asdict method
s_dict = s._asdict()
print(s_dict)
Output
Student(roll_number=1, name='Guido Van Rossum', age='50')
name='Guido Van Rossum', roll_number=1, age='50'
name='Guido Van Rossum', roll_number=1, age='50'
{'roll_number': 1, 'name': 'Guido Van Rossum', 'age': '50'}
Advantage of using namedtuple
If we are using list/tuple we know that elements are accessed using index. So inorder to access the item we must know the currect index. But if we are using the namedtuple we can access element using index and a name. This makes code more readable. We can convert namedtuple object easily to dictionary using method called _asdict
Disadvantage
- Additional import
- Additional code
Hope you have learned something from this post. Please share your suggestions at afsal@parseltongue.co.in