What is Set in Python? Operations & Examples Explained

Python Sets Explained

🟒 Python Sets Explained
Complete Guide

Unique · Unordered · Union · Intersection · frozenset · Real-Life

Section 01
What is a Set in Python?

A set in Python is an unordered collection that stores only unique values. Sets are written using curly braces { }. If you add duplicate values to a set, Python automatically removes them. Sets are used when you only want to store distinct items and perform mathematical set operations like union, intersection, and difference.

πŸ’» Example:
Python
fruits  = {"apple", "banana", "mango"}

numbers = {1, 2, 3, 2, 1}  # duplicates removed

print(fruits)

print(numbers)

print(type(fruits))
πŸ‘† Output:
{'apple', 'banana', 'mango'}
{1, 2, 3}
<class 'set'>
Unordered — items have no fixed position
Unique — no duplicate values allowed
Mutable — can add and remove elements
No indexing — cannot access by position
Section 02
Properties of Set (unique, unordered)
PropertyDescription
UniqueDuplicates are automatically removed
UnorderedItems have no guaranteed order
MutableCan add/remove elements
No indexCannot use set[0] — no position access
Hashable itemsItems must be immutable (no lists inside)
Fast lookupChecking membership is very fast
πŸ’» Unique demo:
Python
s = {1, 2, 2, 3, 3, 3, 4}

print(s)   # {1, 2, 3, 4} — duplicates gone!
Section 03
Creating Sets in Python
πŸ’» Different ways to create:
Python
# Method 1 — curly braces

s1 = {1, 2, 3, 4}

# Method 2 — set() constructor

s2 = set([1, 2, 3, 2])  # from list

s3 = set("Python")       # from string

print(s1)   # {1, 2, 3, 4}

print(s2)   # {1, 2, 3}

print(s3)   # {'P','y','t','h','o','n'}
⚠️ To create an empty set, you must use set() — not {}, because {} creates an empty dictionary.
Section 04
Empty Set vs {} Confusion

This is one of the most common mistakes beginners make. In Python, { } creates an empty dictionary, NOT an empty set. To create an empty set you must use the set() constructor.

πŸ’» Example:
Python
# ❌ This creates a dict, NOT a set!

x = {}

print(type(x))   # <class 'dict'>

# ✅ This creates an empty set

y = set()

print(type(y))   # <class 'set'>

# Add items to the empty set

y.add(1)

y.add(2)

print(y)   # {1, 2}
🚨 Always remember: Empty set = set() — Empty dict = {}
Section 05
Adding Elements (add, update)

Use add() to add a single item to a set. Use update() to add multiple items at once from a list, tuple, or another set. If you try to add a duplicate, it is simply ignored — no error is raised.

▶ add() — single item:
Python
s = {1, 2, 3}

s.add(4)

s.add(2)   # duplicate — ignored

print(s)  # {1, 2, 3, 4}
▶ update() — multiple items:
Python
s = {1, 2}

s.update([3, 4, 5])

print(s)   # {1, 2, 3, 4, 5}

# Update from another set

s.update({6, 7})

print(s)   # {1, 2, 3, 4, 5, 6, 7}
Section 06
Removing Elements (remove, discard, pop)

Python provides three methods to remove items — remove() removes a specific value (raises error if not found), discard() removes a value safely (no error if not found), and pop() removes and returns a random item.

Python
s = {1, 2, 3, 4, 5}

# remove() — raises KeyError if not found

s.remove(3)

print(s)     # {1, 2, 4, 5}

# discard() — safe, no error

s.discard(10)  # 10 not in set — no error

print(s)        # {1, 2, 4, 5}

# pop() — removes random item

removed = s.pop()

print("Removed:", removed)
πŸ’‘ Use discard() when you're not sure if the value exists — it is safer than remove().
Section 07
Set Operations (Union, Intersection, Difference, Symmetric Difference)

Python sets support four powerful mathematical operations. These are similar to Venn diagrams in mathematics and are very useful for comparing and combining data collections.

Python — Setup
A = {1, 2, 3, 4}

B = {3, 4, 5, 6}
πŸ”΅ Union ( | ) — all items from both
Python
print(A | B)             # {1,2,3,4,5,6}

print(A.union(B))        # same result
🟒 Intersection ( & ) — common items only
Python
print(A & B)             # {3, 4}

print(A.intersection(B)) # same result
πŸ”΄ Difference ( - ) — in A but not in B
Python
print(A - B)             # {1, 2}

print(A.difference(B))   # same result
🟣 Symmetric Difference ( ^ ) — not in both
Python
print(A ^ B)                      # {1,2,5,6}

print(A.symmetric_difference(B)) # same
Section 08
Subset & Superset

A set A is a subset of set B if all elements of A are also in B. Set B is then a superset of A. Python provides issubset() and issuperset() methods, or you can use <= and >= operators.

πŸ’» Example:
Python
A = {1, 2}

B = {1, 2, 3, 4}

C = {5, 6}

# Is A a subset of B?

print(A.issubset(B))       # True

print(A <= B)               # True

# Is B a superset of A?

print(B.issuperset(A))     # True

print(B >= A)               # True

# Are they disjoint (no common items)?

print(A.isdisjoint(C))     # True
Section 09
Frozen Set (frozenset)

A frozenset is an immutable version of a set. Once created, you cannot add, remove, or change its elements. Because it is immutable and hashable, a frozenset can be used as a dictionary key or as an element inside another set — something a regular set cannot do.

πŸ’» Example:
Python
fs = frozenset([1, 2, 3])

print(fs)              # frozenset({1, 2, 3})

print(type(fs))        # <class 'frozenset'>

# Can be used as dict key

d = {frozenset({1,2}): "pair"}

# Cannot modify — AttributeError!

# fs.add(4)  ← error

# Set operations still work

fs2 = frozenset([2, 3, 4])

print(fs & fs2)         # frozenset({2, 3})
πŸ’‘ frozenset is to set what tuple is to list — the immutable version of the same structure.
Section 10
Looping Through Sets

You can loop through a set using a for loop just like a list or tuple. However, because sets are unordered, the output order may vary each time you run the program. You cannot access set items by index.

πŸ’» Example:
Python
colors = {"red", "green", "blue"}

for color in colors:

    print(color)
πŸ‘† Output (order may vary):
red
green
blue
πŸ’» Membership check in loop:
Python
nums = {1, 2, 3, 4, 5}

# Print only even numbers

for n in nums:

    if n % 2 == 0:

        print(n)   # 2, 4
⚠️ You CANNOT use index with sets: s[0] causes a TypeError.
Section 11
Set Methods (all important ones)
MethodDescription
add()Add one item
update()Add multiple items
remove()Remove item (error if not found)
discard()Remove item safely (no error)
pop()Remove and return random item
clear()Remove all items
copy()Make a copy of the set
union()All items from both sets
intersection()Common items only
difference()Items in A not in B
symmetric_difference()Items not in both
issubset()Check if subset
issuperset()Check if superset
isdisjoint()Check if no common items
Section 12
Removing Duplicates using Set

One of the most practical uses of sets is removing duplicates from a list. Since sets only keep unique values, converting a list to a set and back to a list instantly removes all duplicates. This is the simplest and fastest way to deduplicate data in Python.

πŸ’» Example:
Python
nums   = [1, 2, 2, 3, 4, 3, 5, 1]

unique = list(set(nums))

print(unique)   # [1, 2, 3, 4, 5]

# Remove duplicates from names list

names = ["Ali", "Sara", "Ali", "John", "Sara"]

unique_names = list(set(names))

print(unique_names)
πŸ‘† Output:
[1, 2, 3, 4, 5]
['Ali', 'Sara', 'John']
⚠️ After converting, the order may change. Use sorted() if order matters: sorted(set(nums))
Section 13
Real-Life Example (Duplicate Emails Filter)

Here is a real-world example — a duplicate email filter. When users sign up, emails may be submitted multiple times. Using a set, we can instantly find unique emails, shared emails between two lists, and emails that are only in one list.

πŸ’» Email Filter Example:
Python
list1 = ["ali@mail.com", "sara@mail.com",

          "john@mail.com", "ali@mail.com"]

list2 = ["sara@mail.com", "maya@mail.com",

          "john@mail.com"]

# Remove duplicates from list1

unique = set(list1)

print("Unique emails:", len(unique))

# Common in both lists

common = set(list1) & set(list2)

print("In both lists:", common)

# Only in list1

only_l1 = set(list1) - set(list2)

print("Only in list1:", only_l1)

# All unique emails from both

all_unique = set(list1) | set(list2)

print("All unique:", all_unique)
πŸ‘† Output:
Unique emails: 3
In both lists: {'sara@mail.com', 'john@mail.com'}
Only in list1: {'ali@mail.com'}
All unique: {'ali@mail.com', 'sara@mail.com', 'john@mail.com', 'maya@mail.com'}
Section 14
Advantages & Limitations of Sets
✅ Advantages:
Auto-removes duplicates — unique values guaranteed
Fast lookup — checking x in set is O(1)
Set operations — powerful union, intersection, difference
Clean deduplication — remove duplicates from any list
Memory efficient — faster than lists for membership tests
❌ Limitations:
Unordered — cannot control item order
No indexing — cannot use set[0]
No duplicates — cannot store same value twice
Immutable items only — cannot store lists inside a set
No slicingset[1:3] is not possible
Section 15
Common Errors in Sets
❌ Error 1 — {} creates dict not set:
Python
s = {}

print(type(s))   # dict — not set!

# Fix: s = set()
❌ Error 2 — Indexing a set:
Python
s = {1, 2, 3}

print(s[0])   # TypeError — no indexing!

# Fix: convert to list first

print(list(s)[0])
❌ Error 3 — Adding mutable item (list):
Python
s = {1, 2}

s.add([3, 4])   # TypeError!

# Fix: add tuple instead

s.add((3, 4))   # ✅
❌ Error 4 — remove() on missing item:
Python
s = {1, 2, 3}

s.remove(99)   # KeyError!

# Fix: use discard()

s.discard(99)  # ✅ no error
🌟 Final Tip: Use sets whenever you need unique values, fast lookups, or mathematical set operations. They are perfect for deduplication tasks!
Python Sets Union Intersection frozenset Beginner
Python Sets — Fast, Unique, and Powerful!

Comments