Day 24/100: Sets and Set Operations in Python
 Rahul Gupta

Rahul Gupta @therahul_gupta

About: I am Software Engineer

Joined:
Jun 5, 2022

Day 24/100: Sets and Set Operations in Python

Publish Date: Jul 15
0 0

Welcome to Day 24 of the 100 Days of Python series!
Today we dive into a unique and powerful Python data structure: the set.

Sets are great when you want to store unique items, remove duplicates, or perform mathematical operations like unions, intersections, and differences.

Let’s explore how sets work and where to use them! 🐍


📦 What You’ll Learn

  • What sets are and how to create them
  • How sets differ from lists and tuples
  • Built-in set methods
  • Set operations: union, intersection, difference, symmetric difference
  • Real-world use cases

🔹 1. What is a Set?

A set is an unordered, mutable, and unindexed collection that does not allow duplicate values.

🔹 Syntax:

my_set = {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

You can also create an empty set using the set() constructor:

empty_set = set()
Enter fullscreen mode Exit fullscreen mode

⚠️ {} creates an empty dictionary, not a set!


✅ 2. Why Use Sets?

  • Automatically removes duplicates
  • Great for membership testing (in)
  • Super efficient for mathematical operations
  • Ideal for comparing groups of values

🔧 3. Basic Set Operations

Create a Set

fruits = {"apple", "banana", "cherry"}
Enter fullscreen mode Exit fullscreen mode

Add Items

fruits.add("orange")
Enter fullscreen mode Exit fullscreen mode

Remove Items

fruits.remove("banana")     # Raises error if not found
fruits.discard("banana")    # Safe removal (no error)
Enter fullscreen mode Exit fullscreen mode

Clear All Items

fruits.clear()
Enter fullscreen mode Exit fullscreen mode

Copy a Set

new_set = fruits.copy()
Enter fullscreen mode Exit fullscreen mode

🔁 4. Set Looping

for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

Note: Since sets are unordered, the output may not follow insertion order.


🔀 5. Set Operations

Let’s take two sets:

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
Enter fullscreen mode Exit fullscreen mode

🔸 Union – All unique items

print(a | b)              # {1, 2, 3, 4, 5, 6}
print(a.union(b))         # Same result
Enter fullscreen mode Exit fullscreen mode

🔸 Intersection – Common items

print(a & b)              # {3, 4}
print(a.intersection(b))  # Same result
Enter fullscreen mode Exit fullscreen mode

🔸 Difference – Items in A but not in B

print(a - b)              # {1, 2}
print(a.difference(b))    # Same result
Enter fullscreen mode Exit fullscreen mode

🔸 Symmetric Difference – Items in A or B, but not both

print(a ^ b)                      # {1, 2, 5, 6}
print(a.symmetric_difference(b)) # Same
Enter fullscreen mode Exit fullscreen mode

🔎 6. Membership Testing

print(3 in a)     # True
print(10 in a)    # False
Enter fullscreen mode Exit fullscreen mode

This is faster in sets than in lists!


⚠️ 7. Sets vs Other Collections

Feature List Tuple Set
Ordered
Mutable
Allows Duplicates
Indexable
Fast Membership

🧪 Real-World Examples

1. Removing Duplicates from a List

nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = list(set(nums))
print(unique_nums)  # [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

2. Checking Common Interests

alice_hobbies = {"reading", "coding", "traveling"}
bob_hobbies = {"coding", "gaming"}

common = alice_hobbies & bob_hobbies
print(common)  # {'coding'}
Enter fullscreen mode Exit fullscreen mode

3. Unique Words in a Sentence

sentence = "this is a test this is only a test"
unique_words = set(sentence.split())
print(unique_words)
Enter fullscreen mode Exit fullscreen mode

🧠 Recap

Today you learned:

  • What sets are and how to create and modify them
  • That sets remove duplicates and speed up membership tests
  • Set operations: union, intersection, difference, and more
  • Real-world examples using sets for cleaning and comparison

Comments 0 total

    Add comment