Sets
Python Sets: The "Unique Collector"
Imagine you have a big bag of marbles, and you want to know which different colors you have. You don't care if you have ten blues; you just want to know that "Blue" is there. In Python, we use a set to keep a collection of items where every single one is one-of-a-kind.
What is a Set?
A set is a collection that is unordered, unindexed, and most importantly, only contains unique items.
-
No Duplicates: If you try to add the same number twice, the set will automatically delete the extra one.
-
Curly Braces: We create sets using { } brackets.
-
Unordered: Python doesn't remember what order you put things in. It's like a messy toy box—everything is in there, but not in a neat line.
-
No Index: Since there is no order, you cannot ask for "item number 0."
Real-World Set Scenarios
-
Student IDs: Making sure no two students have the same ID number.
-
Data Cleaning: Taking a long list of words and removing all the repeats.
-
Common Interests: Finding which hobbies two friends both share (Intersection).
-
Website Tags: Managing a list of unique tags for a blog post.
How it Looks (Syntax & Examples)
The Pattern:
set_name = {item1, item2, item3}
Example 1: Removing Duplicates Automatically
nums = {1, 2, 2, 3}
print(nums)
Output: {1, 2, 3}
Example 2: Finding Common Items (Intersection)
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b)
Output: {3}
Summary:
-
Duplicate Destroyer: Use a set whenever you want to get rid of repeat values instantly.
-
Math Magic: Sets are great for "set math" like finding things that are in both groups (Intersection) or combining groups (Union).
-
Speed: Sets are incredibly fast for checking if an item is "in" the collection.