Some text some message..
Back 8. 🟣 Python Sets – A Detailed Explanation 21 Jun, 2025

🟣 Python Sets – A Detailed Explanation


🔹 What is a Set in Python?

A set is a built-in Python data structure that is:

  • Unordered: No guaranteed order of elements

  • Unindexed: No indexing or slicing

  • Mutable: You can add/remove elements

  • No Duplicates: Automatically removes duplicate values

✅ Think of a set as a collection of unique items, like a bag of distinct balls.


🔹 How to Create a Set

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

# OR using the set() constructor
new_set = set([1, 2, 2, 3])
print(new_set)  # Output: {1, 2, 3}

❌ You cannot create an empty set using {} → this creates a dictionary.
Use set() instead.


🔹 Key Set Properties

Property Description
Unordered Elements have no fixed position
Unique No duplicate values allowed
Mutable Can add or remove elements
Iterable Can loop through it

🔹 Accessing Elements

for item in my_set:
    print(item)

❌ No indexing like my_set[0] — it will raise an error.


🔹 Adding and Removing Elements

my_set.add(5)           # Add one item
my_set.update([6, 7])   # Add multiple items

my_set.remove(2)        # Remove item (raises error if not found)
my_set.discard(10)      # Remove item (no error if not found)

my_set.pop()            # Remove and return random item
my_set.clear()          # Remove all items

🔹 Set Operations (Like in Math)

A = {1, 2, 3}
B = {3, 4, 5}

print(A | B)      # Union: {1, 2, 3, 4, 5}
print(A & B)      # Intersection: {3}
print(A - B)      # Difference: {1, 2}
print(A ^ B)      # Symmetric Difference: {1, 2, 4, 5}

🔹 Set Comparison

A = {1, 2}
B = {1, 2, 3}

print(A.issubset(B))     # True
print(B.issuperset(A))   # True
print(A.isdisjoint({4})) # True (no common elements)

🔹 Set vs List

Feature List Set
Ordered Yes No
Duplicates Allowed Not allowed
Indexing Yes No
Performance Slower lookups Faster (hashed)

🧠 Real-Life Analogy

A set is like a guest list at a private event:

  • You can’t invite the same person twice.

  • You don’t care about the order of arrival.

  • You just want to know who’s coming.


✅ Summary

  • Sets store unique, unordered values.

  • Great for membership tests, removing duplicates, and set operations.

  • Use add(), remove(), and update() for modifications.