
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Private Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Walrus Operator
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python - Floating Points
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Packing and Unpacking
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Namedtuple
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Multiple Inheritance
- Python - Multilevel Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python - Data Classes
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Warnings
- Python - Built-in Exceptions
- Python - Debugger (PDB)
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Generator Expressions
- Python - Lambda Expressions
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - Odds and Ends
- Python - GUIs
- Python Advanced Concepts
- Python - Abstract Base Classes
- Python - Custom Exceptions
- Python - Higher Order Functions
- Python - Object Internals
- Python - Memory Management
- Python - Metaclasses
- Python - Metaprogramming with Metaclasses
- Python - Mocking and Stubbing
- Python - Monkey Patching
- Python - Signal Handling
- Python - Type Hints
- Python - Automation Tutorial
- Python - Humanize Package
- Python - Context Managers
- Python - Coroutines
- Python - Descriptors
- Python - Diagnosing and Fixing Memory Leaks
- Python - Immutable Data Structures
- Python Useful Resources
- Python - Questions & Answers
- Python - Interview Questions & Answers
- Python - Online Quiz
- Python - Quick Guide
- Python - Reference
- Python - Cheatsheet
- Python - Projects
- Python - Useful Resources
- Python - Discussion
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
Python - NamedTuple
In Python,tuples are immutable data structures that can hold a collection of items. We already discussed tuples, it's properties and usage in the previous chapters. In this chapter, we will explainnamedtuple() and its usage in Python.
What is NamedTuple?
In Python, anamedtuple() is a subclass oftuple that allows you to create tuples with named fields. Meaning, you can access the elements of the tuple using fieldnames instead of just numerical indices. It is part of thecollections module in Python.
Syntax
from collections import namedtuple # Define a namedtuplePoint = namedtuple('typename', fieldnames )- Type Name: The typename is the name of the namedtuple class. It is a string that represents the name of the tuple type.
- Field Names: The field names are the names of the elements in the tuple. They are defined as a list of strings.
Create a NamedTuple in Python
To create a namedtuple, you need to import thenamedtuple function from thecollections module. Then, you can define a namedtuple by specifying its name and field names.
The followingexample shows how to create a namedtuple calledPoint with fieldsx andy −
from collections import namedtuple# Define a namedtupleVertex = namedtuple('Vertex', ['x', 'y'])# Create an instancev = Vertex(10, 20)# Access fieldsprint("Vertex-1:", v.x)print("Vertex-2:", v.y)Theoutput of the above code will be −
Vertex-1: 10Vertex-2: 20
Access NamedTuple Fields
We already saw how to access the fields of a namedtuple using dot notation(i.e., using keyname). There are some other ways to access the fields as well −
- Accessing by Indexing − You can access the fields using their index, just like a regular tuple.
- Accessing by keyname − You can also access the fields using their key names, similar to a dictionary.
- Accessing Using getattr() − You can use thegetattr() function to access the fields by name.
Example: Accessing by Indexing
In this example, we will access the fields of the namedtuple using their index.
from collections import namedtuple# Define a namedtuplePoint = namedtuple('Point', ['x', 'y'])# Create an instancep = Point(10, 20)# Access fields by indexingprint("Point-1", p[0])print("Point-2", p[1])Theoutput of the above code will be −
Point-1 10Point-2 20
Example: Accessing by keyname
In this example, we will access the fields of the namedtuple using their key names.
from collections import namedtuple# Define a namedtuplePoint = namedtuple('Point', ['x', 'y'])# Create an instancep = Point(10, 20)# Access fields by keynameprint("Point-1:", p.x)print("Point-2:", p.y)Theoutput of the above code will be −
Point-1: 10Point-2: 20
Example: Accessing Using getattr()
In this example, we will access the fields of the namedtuple using thegetattr() function.
from collections import namedtuple# Define a namedtuplePoint = namedtuple('Point', ['x', 'y'])# Create an instancep = Point(10, 20) # Access fields using getattr()print("getattr(p, 'x'):", getattr(p, 'x'))print("getattr(p, 'y'):", getattr(p, 'y'))Theoutput of the above code will be −
getattr(p, 'x'): 10getattr(p, 'y'): 20
NamedTuple Methods
Namedtuples come with additional built-in methods to handle common operations. The section below discusses some of these methods with examples.
The _fields() method
The_fields() method is used to access the field names of the namedtuple. It doesn't need any arguments and returns a tuple of the field names.
The followingexample demonstrates how to use the_fields() method −
from collections import namedtuple# Define a namedtuplePoint = namedtuple('Point', ['x', 'y'])# Create an instancep = Point(10, 20)# Access fields using _fields()print("Fields of p:", p._fields)Theoutput of the above code will be −
Fields of p: ('x', 'y')The _replace() method
The_replace() method is used to create a new instance of the namedtuple with one or more fields replaced with new values. It takes keyword arguments where the keys are the field names and the values are the new values to be assigned.
The followingexample demonstrates how to use the_replace() method −
from collections import namedtuple# Define a namedtuplePoint = namedtuple('Point', ['x', 'y'])# Create an instancep = Point(10, 20)# Replace a field valuep2 = p._replace(x=30)# Access fieldsprint("p2.x:", p2.x)print("p2.y:", p2.y)Theoutput of the above code will be −
p2.x: 30p2.y: 20
The _asdict() method
The_asdict() method is used to convert the namedtuple into a regular dictionary. This function returns the OrderedDict() as constructed from the mapped values of namedtuple().
The followingexample demonstrates how to use the_asdict() method −
from collections import namedtuple# Define a namedtuplePoint = namedtuple('Point', ['x', 'y'])# Create an instancep = Point(10, 20)# Convert to dictionaryd = p._asdict()print(d)Theoutput of the above code will be −
{'x': 10, 'y': 20}The _make() method
The_make() method is used to create a new instance of the namedtuple from an iterable (like a list or a tuple).
The followingexample demonstrates how to use the_make() method −
from collections import namedtuple# Define a namedtuplePoint = namedtuple('Point', ['x', 'y'])# Create an instancep = Point(10, 20)# Create a new instance using _make()p2 = Point._make([30, 40])# Access fieldsprint("p2.x:", p2.x)print("p2.y:", p2.y)Theoutput of the above code will be −
p2.x: 30p2.y: 40
The ** (double star) operator
The** (double star) operator is used to unpack the fields of the namedtuple into keyword arguments. This can be useful when you want to pass the fields of a namedtuple to a function that accepts keyword arguments.
The followingexample demonstrates how to use the** operator −
import collections# Declaring namedtuple()Student = collections.namedtuple('Student', ['name', 'age', 'DOB'])# Adding valuesS = Student('farhan', '23', '2541997')# initializing iterableli = ['nishu', '19', '411997']# initializing dictdi = {'name': "ravi", 'age': 24, 'DOB': '1391997'}# using ** operator to return namedtuple from dictionaryprint("The namedtuple instance from dict is : ")print(Student(**di))Theoutput of the above code will be −
The namedtuple instance from dict is :Student(name='ravi', age=24, DOB='1391997')
NamedTuple vs Dictionary vs Classes
The main differences between NamedTuple, Dictionary, and Classes are as follows −
| Feature | NamedTuple | Dictionary | Class |
|---|---|---|---|
| Syntax | Simple, just like tuple | Key value pairs | More complex, with methods and attributes |
| Accessing Elements | By name or index | By key | By attribute |
| Mutability | Immutable | Mutable | Mutable |
| Memory Efficiency | Most efficient | Less efficient | Least efficient |
Conclusion
In this chapter, we have learned about namedtuples in Python, and it's differences from dictionaries and classes. A common question arise is that, when to use NamedTuple, Dictionary, or a Class? TheNamedTuple can be used when you need an immutable object with fixed fields, i.e., if you want features of both tuples and dictionaries. TheDictionary can be used when you need a mutable object with dynamic keys. andClass is used when you need a complex data structure with methods and behavior.