1 C Set
1 C Set
Both are used to store unique items and perform mathematical operations like union, intersection, and difference.
1. Set (set)
A set is an unordered collection of unique elements enclosed in curly braces {} or created using the set() function.
Characteristics of Sets:
Creating a Set
# Creating sets
set1 = {1, 2, 3, 4, 5} # Using curly braces
set2 = set([3, 4, 5, 6, 7]) # Using set() function
3. Checking Membership
fruits = {"apple", "banana", "cherry"}
2. Frozenset (frozenset)
A frozenset is an immutable version of a set. Once created, elements cannot be added or removed.
Characteristics of Frozenset:
Creating a Frozenset
# Creating a frozenset
fset = frozenset([1, 2, 3, 4, 5])
print(fset) # Output: frozenset({1, 2, 3, 4, 5})
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers) # Removes duplicates
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
Summary
Feature Set (set) Frozenset (frozenset)
Mutable? ✅ Yes ❌ No
Ordered? ❌ No ❌ No