Named tuple¶
True to its name, it has named fields. How convenient!
In [ ]:
from collections import namedtuple
rectangle = namedtuple('rectangle', 'length width')
r = rectangle(length = 1, width = 2)
print(r)
print(r.length)
print(r.width)
print(r._fields)
rectangle(length=1, width=2)
1
2
('length', 'width')
What is the difference between a list and a tuple? How are lists and tuples stored in memory?
A list is a mutable collection of objects of arbitrary types. The internal structure of a list is a dynamic array of pointers.
A tuple is also a list, but immutable. A tuple containing the same data as a list takes up less memory.