Difference between tuples and frozensets in Python

tuples are immutable lists, frozensets are immutable sets.

tuples are indeed an ordered collection of objects, but they can contain duplicates and unhashable objects, and have slice functionality

frozensets aren't indexed, but you have the functionality of sets - O(1) element lookups, and functionality such as unions and intersections. They also can't contain duplicates, like their mutable counterparts.


Somewhat counter intuitive - what about this bon mot:

sss = frozenset('abc')
sss |= set('efg')

Will yield:

frozenset(['a', 'c', 'b', 'e', 'g', 'f'])

Of course, this is equivalent to x = x | y, so not changing the original frozenset, but it doesn't half make a mockery of the term 'immutable' to the code reviewer!


One difference that comes to mind is the issue of duplicates. A tuple of (1, 1, 1, 1, 2, 2, 2) would be exactly what you expect, but a frozenset would remove all of those duplicates, leaving you with frozenset([1, 2]).