Data Structures in Python - Episode 4: Sets and Frozensets
Introduction
Sets are unordered collections of unique elements in Python. They are extremely useful when you need to eliminate duplicates or perform set operations like union, intersection, and difference.
Example 1: Creating a Set
# Creating a set
my_set = {1, 2, 3, 4, 5}
print(my_set)
Example 2: Set Operations
# Set operations
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print("Union:", set_a | set_b)
print("Intersection:", set_a & set_b)
print("Difference:", set_a - set_b)
What is a Frozenset?
A frozenset is just like a set, but it is immutable — meaning you cannot change its elements after creation.
# Creating a frozenset
frozen = frozenset([1, 2, 3, 4])
print(frozen)
Quick Recap
| Data Structure | Changeable? | Ordered? | Allows Duplicates? |
|---|---|---|---|
| Set | Yes | No | No |
| Frozenset | No | No | No |
Important Notes
Tip: Sets automatically remove duplicate values!
Warning: Sets cannot contain mutable types like lists.
Warning: Sets cannot contain mutable types like lists.
Comments
Post a Comment