In Python, the namedtuple is a class factory provided by the collections module that generates tuple subclasses with named fields. It provides all the functionality of a tuple, but with more readability and self-documentation due to its named fields. It is especially useful when you want immutable, lightweight, and readable data structures that behave like regular classes without the need to define an entire class manually.
The namedtuple function returns a new tuple subclass named by the user, with named fields accessible via dot notation as well as the traditional tuple indexing. It is ideal for creating small, immutable, class-like objects in a compact and memory-efficient manner.
from collections import namedtuple
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)
print(p1.x, p1.y)
print(p1[0], p1[1])
Person = namedtuple('Person', ['name', 'age', 'gender'])
john = Person('John Doe', 30, 'Male')
print(john.name)
print(john[0])
Car = namedtuple('Car', ['brand', 'model', 'year'])
Car = namedtuple('Car', 'brand model year')
Employee = namedtuple('Employee', ['name', 'dept', 'salary'], defaults=['HR', 30000])
emp = Employee('Alice')
print(emp)
Creates an instance from an iterable like a list or tuple.
Point = namedtuple('Point', 'x y')
p = Point._make([3, 4])
print(p)
Returns a dictionary representation of the namedtuple.
print(p._asdict())
Returns a new namedtuple with specified fields replaced.
p2 = p._replace(x=10)
print(p2)
Returns a tuple of field names.
print(p._fields)
Student = namedtuple('Student', 'name grade')
students = [
Student('Alice', 'A'),
Student('Bob', 'B'),
Student('Charlie', 'A'),
]
for s in students:
print(f"{s.name} scored {s.grade}")
Rectangle = namedtuple('Rectangle', 'length width')
rect = Rectangle(10, 5)
l, w = rect
print("Length:", l)
print("Width:", w)
employee = {'name': 'Tom', 'role': 'Manager'}
print(employee['name'])
class Employee:
def __init__(self, name, role):
self.name = name
self.role = role
e = Employee('Tom', 'Manager')
print(e.name)
Employee = namedtuple('Employee', 'name role')
e = Employee('Tom', 'Manager')
print(e.name)
namedtuple is significantly faster than regular class instantiation and uses less memory.
from collections import namedtuple
import time
Point = namedtuple('Point', 'x y')
start = time.time()
for _ in range(1000000):
p = Point(10, 20)
end = time.time()
print("namedtuple time:", end - start)
Student = namedtuple('Student', ['id', 'name', 'grade'])
students = [
Student(101, 'Alice', 'A'),
Student(102, 'Bob', 'B'),
Student(103, 'Charlie', 'A'),
]
for s in students:
print(s._asdict())
fields = ['name', 'class', 'score']
# class is a keyword, rename will rename it
Student = namedtuple('Student', fields, rename=True)
s = Student('Alice', '10A', 95)
print(s)
Person = namedtuple('Person', 'name age city', defaults=['Unknown'])
p = Person('John', 30)
print(p)
import json
from collections import namedtuple
json_data = '{"name": "Alice", "age": 30}'
data = json.loads(json_data)
Person = namedtuple('Person', data.keys())
person = Person(*data.values())
print(person)
Address = namedtuple('Address', 'city state')
Employee = namedtuple('Employee', 'name address')
emp = Employee('John', Address('New York', 'NY'))
print(emp.address.city)
Since namedtuples are immutable, use _replace to modify fields.
Book = namedtuple('Book', 'title author')
book1 = Book('Python 101', 'Guido')
book2 = book1._replace(author='Rossum')
print(book2)
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(1, 2)
print(p)
Python's namedtuple is an incredibly useful feature for creating lightweight, immutable, and readable data structures. It eliminates the need for verbose class definitions while giving the benefits of attribute-based access. Whether you are designing coordinate systems, parsing structured records, or building functional-style applications, namedtuples offer clarity and performance.
Key Takeaways:
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved