๐ Python Sets Made Easy: A Complete Beginner-to-Pro Guide
Python offers powerful built-in data types — and set
is one of the most useful when working with unique values and set operations like union, intersection, and difference.
Let’s explore what sets are, how they work in Python, and where you can use them effectively.
๐ฆ What is a Set in Python?
A set is an unordered, unindexed collection of unique elements.
It’s great for removing duplicates, checking membership, and performing mathematical set operations.
my_set = {1, 2, 3, 4}
print(my_set)
✅ Output:
{1, 2, 3, 4}
⚙️ Creating Sets in Python
1. Using Curly Braces
fruits = {"apple", "banana", "orange"}
2. Using the set()
Constructor
numbers = set([1, 2, 3, 4])
❌ Duplicates Are Removed Automatically
data = {1, 2, 2, 3}
print(data) # Output: {1, 2, 3}
๐ Key Features of Sets
Feature | Description |
---|---|
Unordered | Items do not have a fixed index |
Unique items | No duplicate values |
Mutable | You can add or remove items |
Iterable | Can be looped through like lists |
๐งช Basic Set Operations
๐ Add Elements
my_set = {1, 2}
my_set.add(3)
print(my_set) # {1, 2, 3}
๐ซ Remove Elements
my_set.remove(2) # Raises error if not found
my_set.discard(4) # Safely ignores if not found
✅ Check Membership
if "apple" in fruits:
print("Yes!")
๐ Set Operations (Like Math Sets)
Let’s use two example sets:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
๐ Union (All elements)
print(A | B) # {1, 2, 3, 4, 5, 6}
๐ Intersection (Common elements)
print(A & B) # {3, 4}
➖ Difference (Items in A not in B)
print(A - B) # {1, 2}
⛔ Symmetric Difference (Items not in both)
print(A ^ B) # {1, 2, 5, 6}
๐ง When to Use Sets in Real Projects?
-
๐งน Remove duplicates from a list
-
๐ Fast membership checks (
in
is faster in sets than lists) -
๐ Compare collections of values
-
๐ Data cleaning and deduplication
๐ซ What You Cannot Do with Sets
-
❌ Index or slice (e.g.,
my_set[0]
will cause an error) -
❌ Store mutable items like lists inside a set (because they’re not hashable)
๐ ️ Set vs List vs Tuple – Quick Comparison
Feature | List | Tuple | Set |
---|---|---|---|
Ordered | ✅ | ✅ | ❌ |
Mutable | ✅ | ❌ | ✅ |
Duplicate Values | ✅ | ✅ | ❌ |
Indexed | ✅ | ✅ | ❌ |
๐งช Quick Example: Remove Duplicates from a List
items = [1, 2, 2, 3, 4, 4, 5]
unique_items = list(set(items))
print(unique_items) # [1, 2, 3, 4, 5]
๐งพ Conclusion
Python sets are a powerful tool for handling unique data, cleaning up collections, and doing fast comparisons. They're simple, but with many real-world uses in data science, web development, and automation.
If you know lists and dictionaries — learning sets gives you another handy tool in your Python toolkit.
No comments:
Post a Comment