Modules in Python: namedtuple
Let's discover namedtuple and its functions.
We'll cover the following...
Overview of namedtuple
Let’s discuss the namedtuple
class from the collection module which we can use to replace Python’s tuple.
Of course, the namedtuple
is not a drop-in replacement as we will see soon.
We have
seen some programmers use it like a struct. If we haven’t used a language with a struct in it, then that needs a little explanation.
A
struct is basically a complex data type that groups a list of variables
under one name.
Creating namedtuple
Let’s look at an example of how to create a namedtuple
so we can see how they work:
Press + to interact
from collections import namedtupleParts = namedtuple("Parts", "id_num desc cost amount")auto_parts = Parts(id_num="1234", desc="Ford Engine", cost=1200.00, amount=10)print(auto_parts.id_num)
Here we import namedtuple
from the ...