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! ๐Ÿ’ป✨


No comments:

Post a Comment

๐ŸŽฎ Build Your Own Tic Tac Toe Game Using Python – For Beginers

 Do you love playing Tic Tac Toe ? Today, we’ll show you how to build your very own Tic Tac Toe game in Python — no advanced skills needed!...