The NamedTuple class of the typing module added in Python 3.6 is the younger sibling of the namedtuple class in the collections module. The main difference being an updated syntax for defining new record types and added support for type hints. Like dictionaries, NamedTuples contain keys that are hashed to a particular value. But on the contrary, it supports both access from key-value and iteration, the functionality that dictionaries lack.
Creating a NamedTuple
NamedTuple can be created using the following syntax:
class class_name(NamedTuple): field1: datatype field2: datatype
This is equivalent to:
class_name = collections.namedtuple('class_name', ['field1', 'field2'])
Website(name='GeeksforGeeks', url='geeksforgeeks.org', rating=5)
- Access by index: The attribute values of namedtuple() are ordered and can be accessed using the index number, unlike dictionaries that are not accessible by index.
- Access by keyname: Access by key name is also allowed as in dictionaries.
- using getattr(): This is yet another way to access the value by giving namedtuple and key-value as its argument.
The name of the website is : GeeksforGeeks The URL of the website is : geeksforgeeks.org The rating of the website is : 5
The fields are immutable. So if we try to change the values, we get the attribute error:
AttributeError: can't set attribute
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Data Visualization with Python Seaborn and Pandas
- Type Casting in Python (Implicit and Explicit) with Examples
- How to Add Outline or Edge Color to Histogram in Seaborn?
- Python - Formable Strings Count in Matrix
- Python - Sort Strings by Case difference
- Python - Mean deviation of Elements
- Python - Test if elements of list are in Min/Max range from other list
- Python - Find the sum of Length of Strings at given indices
- Python - Filter rows with only Alphabets from List of Lists
- Python - Find the distance betwewn first and last even elements in a List
- Python - Value limits to keys in Dictionaries List
- Python program to test for Non-neighbours in List
- Python - Element wise Matrix Difference
- Python - Remove Columns of Duplicate Elements
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.