An immutable collection cannot have its contents changed after creation. In Python, a tuple is the immutable counterpart to a list; a frozenset is an immutable set. Strings are immutable sequences too. Immutability does not prevent a variable from being assigned a different object. section 5.7.1 section 3.2.6 section 4.3
Reading is allowed; item assignment is not
x = ('a', 'b', 'c') x[2] # 'c' x[1:] # ('b', 'c') x[2] = 'd' # TypeError: a tuple does not support item assignment Use (1,) for a one-element tuple: the comma matters. tuple([1, 2]) converts a list to a tuple; list((1, 2)) converts it back. section 5.7.1 section 3.2.3
Operations such as tuple concatenation produce another tuple rather than changing the original. String methods likewise return results without changing their string. To make several character edits, convert a string to a list, edit the list, then use "".join() to make a string; doing this repeatedly creates extra objects. section 5.7.1 section 6.4 section 6.4.6
A tuple can hold a mutable object. The tuple cannot replace that element, but the object itself can still change. Such a tuple cannot serve as a dictionary key: keys must be both immutable and hashable. Set members must also be immutable and hashable. section 5.7.1 section 7.4 section 5.8
Table 7.2 Python values eligible to be used as dictionary keys (view table figure)
| Python type |
Immutable? |
Hashable? |
Dictionary key? |
|---|---|---|---|
| int |
Yes |
Yes |
Yes |
| float |
Yes |
Yes |
Yes |
| boolean |
Yes |
Yes |
Yes |
| complex |
Yes |
Yes |
Yes |
| str |
Yes |
Yes |
Yes |
| bytes |
Yes |
Yes |
Yes |
| bytearray |
No |
No |
No |
| list |
No |
No |
No |
| tuple |
Yes |
Sometimes |
Sometimes |
| set |
No |
No |
No |
| frozenset |
Yes |
Yes |
Yes |
| dictionary |
No |
No |
No |
Compare built-in types before choosing a dictionary key: tuples qualify only when their contents are hashable; lists do not qualify, while frozensets do. section 7.4























