Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between tuples and frozensets in Python

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?

like image 755
legends2k Avatar asked Jan 20 '13 07:01

legends2k


People also ask

What is the difference between tuples and lists in Python?

The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.

What is the difference between a Python tuple and Python?

Tuples are immutable whereas lists are mutable in Python Tuples are immutable in Python, which menas that once you have created a tuple the items inside it cannot change. Tuples can't be continually changed. You can't add, replace, reassign, or remove any of the items since tuples can't be changed.

What is the use of Frozenset in Python?

Python frozenset() Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Due to this, frozen sets can be used as keys in Dictionary or as elements of another set.


1 Answers

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.

like image 191
Volatility Avatar answered Sep 23 '22 23:09

Volatility