Python frozenset() Function — A Simple Guide

preview_player
Показать описание

►► Do you want to thrive as a self-employed Python freelancer controlling your own time, income, and work schedule?

⁉️ Do you have a question? Leave a comment and we will answer as soon as possible!

⏰ Subscribe to the channel, never miss a new video!

🐍 Did you know? Finxter is one of the top 10 Python Blogs on the internet!

🚀 More about Python & Freelancing:

#finxter #python

Do you want to thrive as a self-employed Python freelancer controlling your own time, income, and work schedule? Check out our Python freelancer resources:

Finxter Python Freelancer Course:

Finxter Python Freelancer Webinar:

Leaving the Rat Race with Python (Book):
Рекомендации по теме
Комментарии
Автор

I do not think so. frozenset is immutable, but the reason to use frozenset is not because it is imuttable by itself. You could make the same argument for things like dicts, lists, classes.

The primary reason frozenset might be useful, is because frozenset can be hashed. So it can be used as a key into dicts, and sets (and frozens sets). The reason normal set is not-hashable is because it is mutable, and by changing set, it would change hash and equality to other sets, totally breaking set and dict implementation.

So with frozensets you can crated nested sets, which is useful in some algorithms. I.e. parsers, graph traversal, disjoint set, dijkstra, DFS, and few more. Otherwise one would need to do a tedious conversion to tuple and back on each access to a normal set.

For efficiency of hash calculation (we want same hash if sets are equal), frozenset does not preserve insertion order, which is in contrast to normal sets or dicts. frozensets are always "ordered', this ordering is not normal ordering (because one can have non-comparable values in the set, i.e. both strings and integers), but by element hashes. This has two effects: 1) two frozensets will always iterate in same order (during a single execution of the program, orders can be different on different executions, due to random hash seeding on process startup), with same elements, even if elements were added (via iterable) in different initial order. 2) implementation of comparission (as well of union, intersection and difference) is very efficient, because they can traverse two (or more) sets in at the same time, instead of traversing one, and looking in the other, which helps with memory locality and cache prefetching.

movaxh
join shbcf.ru