YouTip LogoYouTip

Python3 Func Frozenset

## Python frozenset() Function The `frozenset()` is a built-in Python function used to create an immutable set object. While a standard Python `set` is mutable (elements can be added, removed, or updated), a `frozenset` is completely **immutable** and **hashable** after creation. Because of these characteristics, a `frozenset` can be used as a key in a dictionary or as an element in another setβ€”operations that are impossible with a standard mutable `set`. --- ## Syntax and Parameters ### Syntax ```python frozenset() ``` ### Parameters * **`iterable`** *(Optional)*: Any iterable object (such as a list, tuple, dictionary, set, or string) whose elements will be used to populate the new `frozenset`. ### Return Value * Returns a new `frozenset` object containing the unique elements from the provided iterable. * If no argument is passed, it returns an empty `frozenset`. --- ## Code Examples ### Example 1: Creating a `frozenset` This example demonstrates how to initialize a `frozenset` using different types of iterables. ```python # 1. Creating a frozenset from a list (duplicates are automatically removed) lst = [1, 2, 3, 2, 1] fs_list = frozenset(lst) print(fs_list) # Output: frozenset({1, 2, 3}) # 2. Creating a frozenset from a string s = "hello" fs_str = frozenset(s) print(fs_str) # Output: frozenset({'h', 'e', 'l', 'o'}) (order may vary) # 3. Creating a frozenset from a dictionary (extracts the keys) d = {"a": 1, "b": 2} fs_dict = frozenset(d) print(fs_dict) # Output: frozenset({'a', 'b'}) # 4. Creating an empty frozenset fs_empty = frozenset() print(fs_empty) # Output: frozenset() ``` **Expected Output:** ```text frozenset({1, 2, 3}) frozenset({'e', 'h', 'l', 'o'}) frozenset({'a', 'b'}) frozenset() ``` **Key Takeaways:** 1. Like standard sets, `frozenset` automatically filters out duplicate values. 2. It can accept any valid Python iterable. 3. Because it is immutable, a `frozenset` does not have mutator methods like `.add()`, `.remove()`, or `.clear()`. --- ### Example 2: Practical Use Cases and Operations Since `frozenset` is hashable, it is commonly used as keys in dictionaries or as elements inside other sets. It also supports standard mathematical set operations. ```python # 1. Using frozenset as a dictionary key d = { frozenset([1, 2]): "Group A", frozenset([3, 4]): "Group B" } print(d) # Output: {frozenset({1, 2}): 'Group A', frozenset({3, 4}): 'Group B'} # 2. Using frozenset as an element inside another set s = {frozenset([1, 2]), frozenset([3, 4])} print(s) # Output: {frozenset({1, 2}), frozenset({3, 4})} # 3. Performing set operations (returns a new frozenset without modifying the originals) fs1 = frozenset([1, 2, 3]) fs2 = frozenset([2, 3, 4]) # Intersection (&) print(fs1 & fs2) # Output: frozenset({2, 3}) # Union (|) print(fs1 | fs2) # Output: frozenset({1, 2, 3, 4}) # Difference (-) print(fs1 - fs2) # Output: frozenset({1}) ``` **Expected Output:** ```text {frozenset({1, 2}): 'Group A', frozenset({3, 4}): 'Group B'} {frozenset({1, 2}), frozenset({3, 4})} frozenset({2, 3}) frozenset({1, 2, 3, 4}) frozenset({1}) ``` --- ## Key Considerations | Feature | `set` | `frozenset` | | :--- | :--- | :--- | | **Mutability** | Mutable (can add/remove elements) | Immutable (cannot be changed after creation) | | **Hashability** | Unhashable (cannot be used as dict keys or set elements) | Hashable (can be used as dict keys or set elements) | | **Common Methods** | `add()`, `remove()`, `pop()`, `clear()`, etc. | `union()`, `intersection()`, `difference()`, `copy()`, etc. | * **Performance**: Because `frozenset` is immutable, Python can optimize its memory allocation, making certain operations slightly faster than a standard mutable `set`. * **Set Operations**: You can perform standard set operations (like union, intersection, and difference) between a `set` and a `frozenset`. The type of the returned set depends on which object is on the left-hand side of the operator.
← Python3 Func ReprPython3 Func Dict β†’