Showing posts with label Python sets explained. Show all posts
Showing posts with label Python sets explained. Show all posts

Thursday, June 12, 2025

🧺 Sets in Python – No Duplicates Allowed!

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

fruits = {"apple", "banana", "cherry"}
print(fruits)

You just made a set! 🎉

📌 Note: Sets use curly braces {} just like dictionaries, but don’t use key-value pairs.


🚫 No Duplicates Allowed

numbers = {1, 2, 3, 2, 4}
print(numbers) # Output: {1, 2, 3, 4}

See? The number 2 only appears once!


🔁 Looping Through a Set

for fruit in fruits:
print(fruit)

The output might be in any order — that’s how sets work!


➕ Adding and ➖ Removing Items

Add an Item

fruits.add("orange")

Remove an Item

fruits.remove("banana")

⚠️ Use discard() if you want to remove an item safely (without error if it doesn’t exist):

fruits.discard("mango")

✨ Useful Set Methods

A = {1, 2, 3}
B = {3, 4, 5} print(A.union(B)) # {1, 2, 3, 4, 5} print(A.intersection(B)) # {3} print(A.difference(B)) # {1, 2}

🎯 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

students = {"Aanya", "Ravi", "Ravi", "Priya"}
print("Unique students:", students)

Output:

Unique students: {'Aanya', 'Ravi', 'Priya'}

🧠 Quick Quiz (Try It!)

  1. What’s the main difference between a list and a set?

  2. Can a set have two items with the same value?

  3. What will this code print?

    s = {1, 2, 3, 1}
    print(len(s))

🏁 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! 💻✨


🚀 Exploring Gemini AI and Python: A Beginner’s Guide for School Students

 Have you ever wondered how your favorite apps recognize your face, suggest videos, or even talk back like a real human? Welcome to the worl...