Frozen Sets in Python
Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.
If no parameters are passed, it returns an empty frozenset.
# Python program to demonstrate
# working of a FrozenSet
# Creating a Set
String = ('G', 'e', 'e', 'k', 's', 'F', 'o', 'r')
Fset1 = frozenset(String)
print("The FrozenSet is: ")
print(Fset1)
# To print Empty Frozen Set
# No parameter is passed
print("\nEmpty FrozenSet: ")
print(frozenset())
Output
The FrozenSet is: frozenset({'F', 's', 'o', 'G', 'r', 'e', 'k'}) Empty FrozenSet: frozenset()
Typecasting Objects into Sets
In this example, lists, strings and dictionaries are converted into sets using the set() constructor, eliminating duplicates in lists and extracting unique elements in strings and dictionary keys.
# Typecasting list into set
my_list = [1, 2, 3, 3, 4, 5, 5, 6, 2]
my_set = set(my_list)
print("my_list as a set: ", my_set)
# Typecasting string into set
my_str = "w3wiki"
my_set1 = set(my_str)
print("my_str as a set: ", my_set1)
# Typecasting dictionary into set
my_dict = {1: "One", 2: "Two", 3: "Three"}
my_set2 = set(my_dict)
print("my_dict as a set: ", my_set2)
Output
my_list as a set: {1, 2, 3, 4, 5, 6} my_str as a set: {'G', 'f', 'r', 'e', 'k', 'o', 's'} my_dict as a set: {1, 2, 3}
Example: Implementing All Functions
In this example, a series of functions demonstrate common operations on sets in Python. These include creating a set, adding and removing elements, clearing the set, performing set union, intersection, difference, symmetric difference, subset, and superset operations.
def create_set():
my_set = {1, 2, 3, 4, 5}
print(my_set)
def add_element():
my_set = {1, 2, 3, 4, 5}
my_set.add(6)
print(my_set)
def remove_element():
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set)
def clear_set():
my_set = {1, 2, 3, 4, 5}
my_set.clear()
print(my_set)
def set_union():
set1 = {1, 2, 3}
set2 = {4, 5, 6}
my_set = set1.union(set2)
print(my_set)
def set_intersection():
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
my_set = set1.intersection(set2)
print(my_set)
def set_difference():
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
my_set = set1.difference(set2)
print(my_set)
def set_symmetric_difference():
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
my_set = set1.symmetric_difference(set2)
print(my_set)
def set_subset():
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 4}
subset = set2.issubset(set1)
print(subset)
def set_superset():
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 4}
superset = set1.issuperset(set2)
print(superset)
if __name__ == '__main__':
create_set()
add_element()
remove_element()
clear_set()
set_union()
set_intersection()
set_difference()
set_symmetric_difference()
set_subset()
set_superset()
Output
{1, 2, 3, 4, 5} {1, 2, 3, 4, 5, 6} {1, 2, 4, 5} set() {1, 2, 3, 4, 5, 6} {4, 5} {1, 2, 3} {1, 2, 3, 6, 7, 8} True True
Advantages of Set in Python
- Unique Elements: Sets can only contain unique elements, so they can be useful for removing duplicates from a collection of data.
- Fast Membership Testing: Sets are optimized for fast membership testing, so they can be useful for determining whether a value is in a collection or not.
- Mathematical Set Operations: Sets support mathematical set operations like union, intersection, and difference, which can be useful for working with sets of data.
- Mutable: Sets are mutable, which means that you can add or remove elements from a set after it has been created.
Disadvantages of Sets in Python
- Unordered: Sets are unordered, which means that you cannot rely on the order of the data in the set. This can make it difficult to access or process data in a specific order.
- Limited Functionality: Sets have limited functionality compared to lists, as they do not support methods like append() or pop(). This can make it more difficult to modify or manipulate data stored in a set.
- Memory Usage: Sets can consume more memory than lists, especially for small datasets. This is because each element in a set requires additional memory to store a hash value.
- Less Commonly Used: Sets are less commonly used than lists and dictionaries in Python, which means that there may be fewer resources or libraries available for working with them. This can make it more difficult to find solutions to problems or to get help with debugging.
Overall, sets can be a useful data structure in Python, especially for removing duplicates or for fast membership testing. However, their lack of ordering and limited functionality can also make them less versatile than lists or dictionaries, so it is important to carefully consider the advantages and disadvantages of using sets when deciding which data structure to use in your Python program.
Set Methods in Python
Function | Description |
---|---|
add() | Adds an element to a set |
remove() | Removes an element from a set. If the element is not present in the set, raise a KeyError |
clear() | Removes all elements form a set |
copy() | Returns a shallow copy of a set |
pop() | Removes and returns an arbitrary set element. Raise KeyError if the set is empty |
update() | Updates a set with the union of itself and others |
union() | Returns the union of sets in a new set |
difference() | Returns the difference of two or more sets as a new set |
difference_update() | Removes all elements of another set from this set |
discard() | Removes an element from set if it is a member. (Do nothing if the element is not in set) |
intersection() | Returns the intersection of two sets as a new set |
intersection_update() | Updates the set with the intersection of itself and another |
isdisjoint() | Returns True if two sets have a null intersection |
issubset() | Returns True if another set contains this set |
issuperset() | Returns True if this set contains another set |
symmetric_difference() | Returns the symmetric difference of two sets as a new set |
symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |
Set Programs
- Program to accept the strings which contains all vowels
- Python program to find common elements in three lists using sets
- Find missing and additional values in two lists
- Pairs of complete strings in two sets
- Check whether a given string is Heterogram or not
- Maximum and Minimum in a Set
- Remove items from Set
- Python Set difference to find lost element from a duplicated array
- Minimum number of subsets with distinct elements using Counter
- Check if two lists have at-least one element common
- Program to count number of vowels using sets in given string
- Difference between two lists
- Python set to check if string is panagram
- Python set operations (union, intersection, difference and symmetric difference)
- Concatenated string with uncommon characters in Python
- Python dictionary, set and counter to check if frequencies can become same
- Using Set() in Python Pangram Checking
- Set update() in Python to do union of n arrays
Useful Links
Python Sets
Python Set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. Here, we will see what is a set in Python and also see different examples of set Python.