Friday, May 3, 2024
HomePythonWhy must you use namedtuple as a substitute of a tuple?

Why must you use namedtuple as a substitute of a tuple?


Hello there guys! You would possibly already be acquainted with tuples. A tuple is a light-weight object kind which permits to retailer a sequence of immutable Python objects. They’re similar to lists however have just a few key variations. The foremost one is that not like lists, you cannot change a price in a tuple. With the intention to entry the worth in a tuple you employ integer indexes like:

man = ('Ali', 30)
print(man[0])
# Output: Ali

Properly, so now what are namedtuples? They flip tuples into handy containers for easy duties. With namedtuples you don’t have to make use of integer indexes for accessing members of a tuple. You may consider namedtuples like dictionaries however not like dictionaries they’re immutable.

from collections import namedtuple

Animal = namedtuple('Animal', 'identify age kind')
perry = Animal(identify="perry", age=31, kind="cat")

print(perry)
# Output: Animal(identify="perry", age=31, kind="cat")

print(perry.identify)
# Output: 'perry'

As you possibly can see that now we will entry members of a tuple simply by their identify utilizing a .. Let’s disect it a little bit extra. A named tuple has two required arguments. They’re the tuple identify and the tuple field_names. Within the above instance our tuple identify was ‘Animal’ and the tuple field_names had been ‘identify’, ‘age’ and ‘cat’.

Namedtuple makes your tuples self-document. You may simply perceive what’s going on by having a fast look at your code. And as you aren’t certain to make use of integer indexes to entry members of a tuple, it makes it easier to take care of your code. Furthermore, as namedtuple situations wouldn’t have per-instance dictionaries, they’re light-weight and require no extra reminiscence than common tuples. This makes them quicker than dictionaries.

Nonetheless, do keep in mind that as with tuples, attributes in namedtuples are immutable. It signifies that this could not work:

from collections import namedtuple

Animal = namedtuple('Animal', 'identify age kind')
perry = Animal(identify="perry", age=31, kind="cat")
perry.age = 42

# Output: Traceback (most up-to-date name final):
#            File "<stdin>", line 1, in <module>
#         AttributeError: cannot set attribute

You need to use named tuples to make your code self-documenting. They’re backwards suitable with regular tuples. It signifies that you should utilize integer indexes with namedtuples as properly:

from collections import namedtuple

Animal = namedtuple('Animal', 'identify age kind')
perry = Animal(identify="perry", age=31, kind="cat")
print(perry[0])
# Output: perry

Final however not the least, you possibly can convert a namedtuple to a dictionary. Like this:

from collections import namedtuple

Animal = namedtuple('Animal', 'identify age kind')
perry = Animal(identify="perry", age=31, kind="cat")
perry._asdict()
# Output: OrderedDict([('name', 'perry'), 
# ('age', 31), ('type', 'cat')])

I’m positive that you simply realized a factor or two in right this moment’s submit! Let me remind you that I’m writing a e-book on Python which would come with issues like this. If you wish to be the primary one to know when it comes out then signup to my mailing record. I additionally ship out a weekly publication containing fascinating and informative hyperlinks associated to Python which I come throughout each week. When you’ve got any query then don’t hesitate to ask! I like to reply 🙂 You may strategy me by means of E-mail, Twitter or Fb. Goodbye!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments