Up to this level of Python, you have learned data structure of Python.
module of Python includes implementations of several data structures
that extend those found in other modules. Gradually you will learn the power of Python collections module.
Let us discuss its power one by one.
Python Named Tuple
So far, we've seen several data types in Python, int, str, list, tuple, dictionary.
But if you want to create your own datatype, Python collection namedtuple give you the way to create the
own data type. In C language you might have used struct to create own data type.
When you want create a new data type, You might want to ask some questions.
What is the name of new datatype, what are the fields of new data type.
Let's discuss the syntax of namedtuple.
collections.namedtuple(typename, field_names[, verbose=False][, rename=False])
- typename it defines the name of new datatype.
- field_names The field_names can be a sequence of strings like ['x', 'y'] or string in which values are white
space or "," separated.
- if verbose=False then class definition would not printed, good idea to remain it false
- if rename=False then invalid fieldnames are automatically replaced with positional names for example 'def, age, empid'
is converted to '_0 , age, empid' becuase def is a keyword
Let us discuss our first example
Now you know how to access namedtuple values.
In Next example you will see, how to add list values into Python namedtuple and how to make dictionary from namedtuple.
You have seen, by using _make
you can add list into a namedtuple and by using _asdict you can create dictionary of named
Consider a situation when you want to replace a value from namedtuple. Like tuple the namedtuple are also imutable.
But you can use _replace method and reassinging, to replace value from namedtuple.
I hope you have enjoyed the chapter. Press like, share and comment.