A frozen set in Python is created using the frozenset() function. It is similar to a normal set, but the main difference is that a frozen set is immutable, which means its elements cannot be changed, added, or removed after it is created. Frozen sets are useful when you want a collection of unique elements that should remain constant during the execution of a program. numbers = frozenset([1, 2, 3, 4, 5]) print(numbers) Output frozenset({1, 2, 3, 4, 5}) In this example, the numbers are stored inside a frozen set and cannot be modified later. Example 2: Frozen Set Removes Duplicate Values Like normal sets, frozen sets store only unique values. If duplicate elements are provided when creating the frozen set, Python automatically removes the repeated values and keeps only one copy of each element. data = frozenset([1, 2, 2, 3, 4, 4, 5]) print(data) Output frozenset({1, 2, 3, 4, 5}) Here, the numbers 2 and 4 appear twice in the list, but the frozen set keeps only one instance of each number. Example 3: Creating Frozen Set from a List Description: A frozen set can be created from different iterable objects such as lists, tuples, or strings. When a list is converted into a frozen set, all its elements become part of an immutable set. my_list = ["apple", "banana", "orange"] fruits = frozenset(my_list) print(fruits) Output frozenset({'apple', 'banana', 'orange'}) In this example, the list of fruits is converted into a frozen set. Example 4: Creating Frozen Set from a String Description: When a string is passed to the frozenset() function, each character in the string becomes an element of the frozen set. Since sets store only unique elements, repeated characters will appear only once. letters = frozenset("python") print(letters) Output frozenset({'p', 'y', 't', 'h', 'o', 'n'}) Each letter of the word python becomes a separate element in the frozen set. Example 5: Frozen Set Union Operation Description: Frozen sets support many mathematical operations such as union, intersection, and difference. The union operation combines the elements of two frozen sets and returns a new frozen set containing all unique elements. A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) print(A.union(B)) Output frozenset({1, 2, 3, 4, 5, 6}) In this example, the union operation merges both frozen sets and removes duplicate elements. #python #pythonforbeginners #pythonprogramming #python #pythondatastructure #pythondatatype #education #intersectionofsets #linkedinfollowers

To view or add a comment, sign in

Explore content categories