In general, you can use namedtuple instances wherever you need a tuple-like object. Named tuples have the advantage that they provide a way to access their values using field names and the dot notation. This will make your code more Pythonic.
Finally, namedtuple s are ordered, unlike regular dict s, so you get the items in the order you defined the fields, unlike a dict . If you need more flexibility, attrs is an interesting alternative to namedtuple. If you're using Python 3.7 or CPython 3.6 dicts are insertion ordered.
Namedtuple makes your tuples self-document. You can easily understand what is going on by having a quick glance at your code. And as you are not bound to use integer indexes to access members of a tuple, it makes it more easy to maintain your code.
Benefits of Python Namedtuple Unlike a regular tuple, python namedtuple can also access values using names of the fields. 2. Python namedtuple is just as memory-efficient as a regular tuple, because it does not have per-instance dictionaries. This is also why it is faster than a dictionary.
In dict
s, only the keys have to be hashable, not the values. namedtuple
s don't have keys, so hashability isn't an issue.
However, they have a more stringent restriction -- their key-equivalents, "field names", have to be strings.
Basically, if you were going to create a bunch of instances of a class like:
class Container:
def __init__(self, name, date, foo, bar):
self.name = name
self.date = date
self.foo = foo
self.bar = bar
mycontainer = Container(name, date, foo, bar)
and not change the attributes after you set them in __init__
, you could instead use
Container = namedtuple('Container', ['name', 'date', 'foo', 'bar'])
mycontainer = Container(name, date, foo, bar)
as a replacement.
Of course, you could create a bunch of dict
s where you used the same keys in each one, but assuming you will have only valid Python identifiers as keys and don't need mutability,
mynamedtuple.fieldname
is prettier than
mydict['fieldname']
and
mynamedtuple = MyNamedTuple(firstvalue, secondvalue)
is prettier than
mydict = {'fieldname': firstvalue, 'secondfield': secondvalue}
Finally, namedtuple
s are ordered, unlike regular dict
s, so you get the items in the order you defined the fields, unlike a dict
.
Tuples are immutable, whether named or not. namedtuple
only makes the access more convenient, by using names instead of indices. You can only use valid identifiers for namedtuple
, it doesn't perform any hashing — it generates a new type instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With