Let’s learn about a super cool data structure in Python called a Set. If you ever wanted to keep a list of things where no item repeats, a set is your best friend! ๐
๐ง What is a Set?
A set in Python is a collection that:
-
✅ Stores multiple items
-
๐ซ Does not allow duplicates
-
๐ Is unordered (the items may appear in any order)
-
๐ก Is changeable (you can add or remove items)
Think of it like a bag of unique marbles — you can toss in many marbles, but never two of the same kind!
๐ ️ How to Create a Set
You just made a set! ๐
๐ Note: Sets use curly braces
{}
just like dictionaries, but don’t use key-value pairs.
๐ซ No Duplicates Allowed
See? The number 2
only appears once!
๐ Looping Through a Set
The output might be in any order — that’s how sets work!
➕ Adding and ➖ Removing Items
Add an Item
Remove an Item
⚠️ Use
discard()
if you want to remove an item safely (without error if it doesn’t exist):
✨ Useful Set Methods
๐ฏ Why Use Sets?
-
To remove duplicates from a list
-
To perform math-like operations (like union, intersection)
-
When order doesn't matter
๐งช Real-Life Example: Unique Students in a Class
Output:
๐ง Quick Quiz (Try It!)
-
What’s the main difference between a list and a set?
-
Can a set have two items with the same value?
-
What will this code print?
๐ Final Thoughts
Sets in Python are simple but powerful! If you want to keep things unique and tidy, sets are the perfect tool. Try using them in your school projects, games, or even mark-sheets!
Keep exploring and keep coding! ๐ป✨
No comments:
Post a Comment