Python Mastery – From Basics to Brilliance / Data Structures in Python

Sets

A set is an unordered collection of unique elements — duplicates are automatically removed.

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

🔍 Why Use Sets?

  • To remove duplicates from data.

  • To perform mathematical set operations like union, intersection, difference.

  • Sets are faster for membership checks (in).


📌 Common Set Operations

set1 = {1, 2, 3}
set2 = {3, 4, 5}

print(set1.union(set2))        # {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # {3}
print(set1.difference(set2))   # {1, 2}
print(set2.difference(set1))   # {4, 5}

🚫 No Indexing in Sets

s = {10, 20, 30}
# print(s[0])  ❌ Error: 'set' object is not subscriptable

Use loops if you want to access items:

for num in s:
    print(num)

🔄 Adding & Removing Items

s = {1, 2}
s.add(3)       # Add single item
s.remove(2)    # Remove item (raises error if not found)
s.discard(5)   # Remove safely (no error if not found)

💡 Real-life Analogy

A set is like a guest list for a party —

even if someone tries to enter twice, they’re only counted once.