What's the difference between frozensets and sets?

620 Views Asked by At

What's the difference between fronzensets/sets and what are their advantages/disadvantages?

2

There are 2 best solutions below

0
lejlot On BEST ANSWER

Frozenset is immutable. Once created you cannot add/remove elements from it. This means that they can be used as keys in dictionaries etc. and in any other place where you would like an object to be hashable. A common practise is to be working with a set while constructing it, and if at any point you know it will no longer change - freeze it for a guarantee of it really not happening.

0
jsbueno On

frozensets are frozen! :-D

Joke apart, the most important characteristic is that they are hashable, and therefore, can be used as dictionary keys!

So, they allow for an incredible thing in Python: dictionaries that can have multiple strings as a single key, no matter the order of those strings.

The objective difference is that once created, a frozenset is not mutable - no new elements can be added and nothing can be removed.

Otherwise, all set operations will work for them (those that would not cause it to be changed, of course) - and, unfortunately, as frozensets have no special syntax for their creation, they are relatively little known by developers.