Reputation: 32964
I'm learning Python 3 using The Quick Python Book, where the author talks about frozensets, stating that since sets are mutable and hence unhashable, thereby becoming unfit for being dictionary keys, their frozen counterparts were introduced. Other than the obvious difference that a tuple is an ordered data structure while frozenset, or more generally a set, is unordered, are there any other differences between a tuple and a frozenset?
Upvotes: 69
Views: 36886
Reputation: 21
A tuple can store duplicate values, while a frozenset enforces uniqueness. Tuples allow element access by index, but frozensets do not support indexing or slicing. Frozensets support set operations like union, intersection, and difference, whereas tuples lack these. Additionally, a tuple's hashability depends on its elements (it must contain only hashable items), while a frozenset is always hashable since it contains only immutable elements. Lastly, tuples preserve insertion order (since Python 3.7+), while frozensets are unordered, meaning iteration order is not guaranteed.
Upvotes: 1
Reputation: 948
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!
Upvotes: 14
Reputation: 8108
Volatility does mention that frozensets are not indexed. I was looking at the other functionality, so did not immediately realize that standard python slicing is not possible.
a = frozenset((1, 1, 1, 1, 2, 2, 2)) # results in frozenset([1, 2])
print a[0]
will give error:
TypeError: 'frozenset' object does not support indexing
Obvious from fact that it is not indexed, but though it was worth adding explicitly here
Upvotes: 5
Reputation: 32310
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.
Upvotes: 114
Reputation: 106470
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])
.
Upvotes: 7