The reasons for having immutable types apply to tuples:
- copy efficiency: rather than copying an immutable object, you can alias it (bind a variable to a reference)
- comparison efficiency: when you're using copy-by-reference, you can compare two variables by comparing location, rather than content
- interning: you need to store at most one copy of any immutable value
- there's no need to synchronize access to immutable objects in concurrent code
- const correctness: some values shouldn't be allowed to change. This (to me) is the main reason for immutable types.
$ python -mtimeit '["fee", "fie", "fo", "fum"]'
1000000 loops, best of 3: 0.432 usec per loop
$ python -mtimeit '("fee", "fie", "fo", "fum")'
10000000 loops, best of 3: 0.0563 usec per loop
>>> t1 = (1,2)
>>> d1 = { t1 : 'three' }
>>> print d1
{(1,2): 'three'}
>>> t1[0] = 0 ## results in a TypeError, as tuples cannot be modified
>>> t1 = (2,3) ## creates a new tuple, does not modify the old one
>>> print d1 ## as seen here, the dict is still intact
{(1,2): 'three'}
Using a tuple, the dictionary is safe from having its keys changed "out from under it" to items which hash to a different value. This is critical to allow efficient implementation.
frozenset:元素一经创建,不可增加、删除和修改。因此没有add、pop、discard、remove和所有以_update结尾的方法。但可以作为左值接受赋值