Python is a simpler programming language compared to others like Java, C#, etc. One reason is that it contains several data structures. One of these data structures and the main focus of this article is the namedtuple of python. We will explore the Python namedtuple, how it works, and why it's efficient.
What is Namedtuple in Python?
A Python namedtuple is an immutable subclass of tuples. It named attributes to access its elements instead of indexes, which are used to access elements in a conventional tuple.
Namedtuples are very useful to create lightweight easy-to-read classes making them simple and efficient in all aspects.
But let's first revisit tuples before diving deep into namedtuple. Tuples are immutable (meaning they cannot be changed) collections of elements, usually in parenthesis and separated by commas. For example, a python code for tuples would look like this:
my_tuple = (1, "apple", True) print(my_tuple[0]) print(my_tuple[1]) print(my_tuple[2])
Output:
1 apple True
In this example, a tuple called my tuple is created and has three elements: the number 1, the word "apple," and the boolean "True." The outputs for the print statements are contained in the remark (after #).
Is a Namedtuple immutable? Yes, a namedtuple is an immutable object. You cannot change its values once it is created. This is because tuples are immutable in Python and namedtuple is one of the subclasses of that data structure.
A namedtuple is a bit different because it functions like a tuple but has named elements. It offers a method for producing an immutable object with a named attribute for each member. They are produced by the namedtuple() function, which is a component of the collections module, and have a distinctive syntax.
Here is an example:
from collections import namedtuple Person = namedtuple('Person', ['name', 'age', 'gender']) person1 = Person(name='Alice', age=25, gender='female') print(person1.name) # Output: "Alice" print(person1.age) # Output: 25 print(person1.gender) # Output: "female"
Output:
Alice 25 female
In the above code, first, we import the ‘namedtuple’ class from the ‘collections’ module. Then we create a namedtuple, called ‘Person’ with the data structure type ‘namedtuple’ and give it three attributes: ‘name’, ‘age’, and ‘gender’. Next, we create an instance of ‘Person’, called ‘person1’ and give it values. Finally, we print out the values of the three attributes of ‘person1.’
Advantages of using Namedtuple
Here are some major advantages of using Namedtuple in Python and why it should be preferred over dictionaries:
- A concise way to create a Class: It can be difficult to set up a class in Python, but it can be easily defined using namedtuples and only a few characteristics. This makes it quick to construct classes and improves the effectiveness of your code.
- Immutable: In programming, immutable means the created object cannot be changed after its creation. It offers a benefit in that it makes the code safer because the user cannot accidentally change any aspect of the immutable object.
- Accessibility: Accessing elements is easier when using namedtuples because it doesn’t use an index. It uses the named attribute to access the elements as necessary.
- Functionality: Built-in methods such as ‘_make()’, and ‘_replace()’ come as part and parcel of the package with namedtuples. They are used to make it easier to work with namedtuples. Also, it is more memory efficient.
- Default Values: It provides a way to set default values for each attribute. By setting default values, the user can avoid the need to set the values of each attribute every time you create an instance.
Python Namedtuple using Default Values
Here is an example of using default values when creating a namedtuple:
from collections import namedtuple Person = namedtuple('Person', ['name', 'age', 'gender']) Person.new.defaults = ('unknown', 0, 'unknown') p1 = Person() print(p1) p2 = Person('John', 25) print(p2)
Output:
Person(name='unknown', age=0, gender='unknown') Person(name='John', age=25, gender=’male’')
In this example, we constructed a namedtuple with the three attributes, ‘name’, ‘age’, and ‘gender’. We then used the ‘new.defaults’ property to set default values for the aforementioned three attributes. The first instance was created with the default (‘unknown’) values and the second was created as a specific person with the value John, a 25-year-old male.
Python Namedtuple using Types
Here is an example of using types in a namedtuple:
from collections import namedtuple Employee = namedtuple('Employee', ['name', 'age', 'job_title']) Employee.annotations = {'age': int} e = Employee('Jane', '30', 'Software Developer') print(e.age) print(type(e.age))
Output:
30 <class 'str'>
In the above section of code, we created a namedtuple called ‘Employee’ and gave it three attributes ’name’, ‘age’, and ‘job_title’. Then we specified the type of the ‘age’ attribute as int.
Next, we constructed an instance of the ‘Employee’ namedtuple and gave it the value, name Jane, a 30-year-old software developer. While printing the instance, we can use the dot notation and verify its type using the python inbuilt function ‘type()’.
Conclusion
Python’s namedtuple is a useful data structure that is memory efficient, easy to read concise, immutable, and so on. Now, with the code to create Namedtuple in Python using values and types with its advantages. Happy Learning :)