Tuple
A tuple consists of a number of values separated by commas, for instance:
> t = 12345, 54321, 'hello!'
> t[0]
12345
> t
(12345, 54321, 'hello!')
> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
> v
([1, 2, 3], [3, 2, 1])
Named Tuple
Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.
from collections import namedtuple
Basic Example
> Point = namedtuple('Point', ['x', 'y'])
> p = Point(11, y=22) # instantiate with positional or keyword arguments
> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
> x, y = p # unpack like a regular tuple
> x, y
(11, 22)
> p.x + p.y # fields also accessible by name
33
> p # readable __repr__ with a name=value style
Point(x=11, y=22)
Make
The popitem() method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false.
> t = [11, 22]
> Point._make(t)
Point(x=11, y=22)
As Dictionary
Return a new dict which maps field names to their corresponding values:
> p = Point(x=11, y=22)
> p._asdict()
{'x': 11, 'y': 22}
Replace
Return a new instance of the named tuple replacing specified fields with new values
> p = Point(x=11, y=22)
> p._replace(x=33)
Point(x=33, y=22)
> for partnum, record in inventory.items():
... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
Fields
Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.
> p = Point(x=11, y=22)
> p._replace(x=33)
Point(x=33, y=22)
> for partnum, record in inventory.items():
... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
Field Defaults
Dictionary mapping field names to default values.
> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
> Account._field_defaults
{'balance': 0}
> Account('premium')
Account(type='premium', balance=0)