Tuples are immutable. So if you need to change objects after creation for any reason, in any way or shape, you can't use namedtuple . You're better off defining a custom class (some of the stuff namedtuple adds for you doesn't even make sense for mutable objects).
Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field. In this case, we have to use another private method _replace() to replace values of the field. The _replace() method will return a new named tuple.
To create a new namedtuple , you need to provide two positional arguments to the function: typename provides the class name for the namedtuple returned by namedtuple() . You need to pass a string with a valid Python identifier to this argument.
The accessing methods of NamedTuple From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.
I am working with a list of namedtuples. I would like to add a field to each named tuple after it has already been created. It seems I can do that by just referencing it as an attribute (as in namedtuple.attribute = 'foo'
), but then it isn't added to the list of fields. Is there any reason why I shouldn't do it this way if I don't do anything with the fields list? Is there a better way to add a field?
>>> from collections import namedtuple >>> result = namedtuple('Result',['x','y']) >>> result.x = 5 >>> result.y = 6 >>> (result.x, result.y) (5, 6) >>> result.description = 'point' >>> (result.x, result.y, result.description) (5, 6, 'point') >>> result._fields ('x', 'y')
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