Tuples
Using tuples brings
clarity: you know its length will never changeperformance: A tuple uses less memory than a list of the same length, and it allows Python to do some optimizations.
Mutable Fields in Tuples
Immutability of a tuple only applies to the references contained in it. References in a tuple cannot be deleted or replaced. But if one of those references points to a mutable object, and that object is changed, then the value of the tuple changes.
Python
>>> a = (10, 'alpha', [1, 2])
>>> b = (10, 'alpha', [1, 2])
>>> a == b
True
>>> b[-1].append(99)
>>> a == b
False
>>> b
(10, 'alpha', [1, 2, 99]) # We've "modified" a tuple.. sorta...Tuples with mutable objects cannot be hashed, thus you cannot use them as dictonary keys.
Python
>>> d = {}
>>> key = (10, [1, 2])
>>> d[key] = 'value'
TypeError: unhashable type: 'list'Named tuples
Pithy
Use case: to build classes of bojects that are just bundles of attributes with no custom methods or you want immutablility.
python
collections.namedtuple('Card', ['rank', 'suit'])
c = Card('7', 'diamonds')
print(c.rank) #7
print(c.suit) #diamonds