
- 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 - 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 - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- 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 - 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 - 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 - 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 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 - Built-in Exceptions
- 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 - 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 - 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 collections.namedtuple
The namedtuple() in Python is a data type from the collections module. It assigns a name to each position in a tuple, allowing elements to be accessed by field names, similar to how we access elements in a tuple by index.
The namedtuple() class returns a new tuple subclass named typename. The new subclass is used to created tuple like objects that have fields accessible by attributes and being indexable and iterable. We can access the elements by typename, field name and by passing index values.
Syntax
Following is the syntax of the Python namedtuple() data type −
class collections.namedtuple(typename, field_names, rename, default)
Parameters
This class accepts following parameters −
typename : It returns a new tuple subclass named typename[name of tuple]. The new subclass is used to created tuple like objects that have fields accessible by attributes and being indexable and iterable. We can access the elements by typename, field name and by passing index values.
field_names: It can be sequence of the strings such as ['x', 'y'] or can be a single string with fieldname separated by white-space or commas. For example, 'x y' or 'x, y'. The field_name can be any python identifiers except the name starting with an underscore or a digit and cannot be a keywords.
rename: If it is true, invalid fieldnames are automatically replaced with positional names. For example, ['xyz', 'class', 'mno', 'pqr'] is converted to ['xyz', '4', 'mno', 'pqr'], eliminated the keyword class keyword.
default: It can be None or an iterable of default values. Since fields with a default value must come after any fields without a default, the defaults are applied to the rightmost parameters. For example, if the fieldnames are ['p', 'q', 'r'] and the defaults are (10,20), then p will be a required argument, q will default to 10, and r will default to 20.
Return Value
This class returns a new subclass tuple.
Example
Following is the basic example of the Python namedtuple() data type −
from collections import namedtuple student1 = namedtuple('student1',['name','rollno', 'marks']) var = student1(name = 'Sai',rollno=237, marks=89) print("Name :",var.name) print("Rollno :",var.rollno) print("Marks :",var.marks)
Following is the output of the above code −
Name : Sai Rollno : 237 Marks : 89
Using namedtuple() with _.make()
The _.make() will initialize values of the existing namedtuple to with a iterable. It accepts the iterable as an argument.
Example
Here, we have created a tuple using namedtuple() and named student1 and replaced the elements of it using make() method −
from collections import namedtuple student1 = namedtuple('student1',['name','rollno', 'marks']) var = student1('John', 202, 75) print(var) tup1 = [12, 45, 89] print(student1._make(tup1))
Following is the output of the above code −
student1(name='John', rollno=202, marks=75) student1(name=12, rollno=45, marks=89)
Using namedtuple() with ._asdict()
The tuple which is created using namedtuple() class can be converted into dictionary by _asdict() method.
Example
Here, we have tuple named dic1 and converted to dictionary using _asdict() method −
from collections import namedtuple dic1 = namedtuple('dic1',['Telangana','TamilNadu', 'Karnataka']) var = dic1('Hyderabad', 'Chennai', 'Bangalore',) print(var._asdict())
Following is the output of the above code −
{'Telangana': 'Hyderabad', 'TamilNadu': 'Chennai', 'Karnataka': 'Bangalore'}
Using namedtuple() with ._replace()
The replace() method returns a new instance of the named tuple replacing specified fields with new values.
Example
Following is an example of usage of replace() with namedtuple −
from collections import namedtuple list1 = namedtuple('list1',['x', 'y']) var = list1(x=10, y=90) print(var._replace(x=55))
Following is the output of the above code −
list1(x=55, y=90)
Using namedtuple() with _field
The _field() method is used to concatenate two namedtuples and the tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.
Example
Here, we have created two tuples and concatenated into a single tuple using _fields and assigned values −
from collections import namedtuple tup1 = namedtuple('tup1',['x1','y1','z1']) tup2 = namedtuple('tup2',['x2','y2','z2']) Newtup = namedtuple('Newtup', tup1._fields + tup2._fields) res = Newtup(12,14,16,18,20,22) print(res)
Following is the output of the above code −
Newtup(x1=12, y1=14, z1=16, x2=18, y2=20, z2=22)
Using namedtuple with _field_defaults
The dictionary mapping field names to default values is done using _field_defaults method in namedtuples. If we pass the arguments less than the defined string list then it take default value for the other argument.
Example
Here, we have created a namedtuple, My_tup1 with 2 fieldnames and given a default value -1. We have passed a single value into the My_tup1 but resulted in 2 values because of _field_defaults() method −
from collections import namedtuple My_tup1 = namedtuple('My_tup1',['val1', 'val2'],defaults=[-1]) res = My_tup1._field_defaults print("default value :",res) print(My_tup1(12))
Following is the output of the above code −
default value : {'val2': -1} My_tup1(val1=12, val2=-1)