🔷 Python Sets 

🔹 1. What is a Set?

A Set is an unordered, unindexed, and mutable collection of unique elements.
Duplicate values are automatically removed.

Sets in Python - PostNetwork Academy

✅ Example:

fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)   # {'apple', 'banana', 'cherry'}
 

✅ Empty Set:

s = set()   # ✅ Correct
s2 = {}     # ❌ Creates an empty dictionary
 

🔹 2. Properties of Sets

PropertyDescription
UnorderedNo fixed position or index
UniqueDuplicate values are removed
MutableYou can add/remove elements
HeterogeneousCan store mixed data types

✅ Example:

data = {10, "Sakshi", 9.4, True}
print(data)
 

🔹 3. Accessing Elements

Since sets are unordered, elements cannot be accessed by index or slicing.

✅ Example:

myset = {1, 2, 3}
for i in myset:
   print(i)
 

🔹 4. Adding Elements

MethodDescriptionExample
add()Add one elements.add(5)
update()Add multiple elementss.update([6,7,8])

✅ Example:

nums = {1, 2, 3}
nums.add(4)
nums.update([5, 6])
print(nums)  # {1, 2, 3, 4, 5, 6}
 

🔹 5. Removing Elements

MethodDescriptionExample
remove(x)Removes element, raises error if not founds.remove(2)
discard(x)Removes element, no error if not founds.discard(10)
pop()Removes random elements.pop()
clear()Removes all elementss.clear()

✅ Example:

nums = {1, 2, 3, 4}
nums.remove(2)
nums.discard(5)   # no error
print(nums)
 

🔹 6. Set Operations 

Python supports mathematical set operations like union, intersection, difference, etc.

Python Set - Learn By Example

Let’s take:

 

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

OperationSymbolMethodResult
Union`AB`A.union(B)
IntersectionA & BA.intersection(B){3,4}
DifferenceA - BA.difference(B){1,2}
Symmetric DifferenceA ^ BA.symmetric_difference(B){1,2,5,6}

✅ Example:

print(A | B)  # Union
print(A & B)  # Intersection
print(A - B)  # Difference
print(A ^ B)  # Symmetric Difference
 

🔹 7. Membership Test

✅ Example:

fruits = {"apple", "banana", "cherry"}
print("banana" in fruits)   # True
print("grape" not in fruits)  # True
 

🔹 8. Copying a Set

✅ Example:

A = {1, 2, 3}
B = A.copy()
print(B)
 

🔹 9. Frozen Sets (Immutable Sets)

A frozenset is an immutable version of a set (cannot be changed after creation).

✅ Example:

A = frozenset([1, 2, 3])
# A.add(4) ❌ Error
print(A)
 

🔹 10. Built-in Set Functions

FunctionDescriptionExample
len()Returns sizelen(s)
max()Largest elementmax({1,3,2})
min()Smallest elementmin({1,3,2})
sum()Sum of numeric elementssum({1,2,3})
sorted()Returns sorted listsorted(s)

🧠 Mini Practice Programs

  1. Create a set of numbers and find union & intersection with another set.
  2. Remove all duplicate elements from a list using a set.
  3. Find elements present in one set but not the other.
  4. Check if one set is a subset of another.
  5. Create two sets of even and odd numbers and find their union.

 

✅ Example: Remove duplicates from a list

nums = [1, 2, 2, 3, 4, 4, 5]
unique = set(nums)
print(unique)  # {1, 2, 3, 4, 5}