✅ Python 3.Set – Explanation
A set in Python is a collection of unique, unordered elements.
⭐ Key Features:
No duplicate values
Unordered (elements don’t have a fixed position)
Mutable (you can add/remove items)
Uses curly braces {} or set() function
📌 Example:
my_set = {1, 2, 3, 4}
print(my_set)
🚫 No Duplicates:
my_set = {1, 2, 2, 3}
print(my_set)
Output: {1, 2, 3}
🔥 Why use a Set?
Fast membership checking (in)
Automatically removes duplicates
Useful for mathematical operations like union, intersection, difference, etc.
📚 Common Inbuilt Functions / Methods of Set in Python
Below is a clean list with examples:
1️⃣ add() — Add an element
s = {1, 2, 3}
s.add(4)
print(s) # {1, 2, 3, 4}
2️⃣ update() — Add multiple items
s = {1, 2}
s.update([3, 4, 5])
print(s) # {1, 2, 3, 4, 5}
3️⃣ remove() — Remove element (gives error if not found)
s = {1, 2, 3}
s.remove(2)
print(s) # {1, 3}
4️⃣ discard() — Remove element (NO error if not found)
s = {1, 2, 3}
s.discard(5) # No error
5️⃣ pop() — Removes and returns a random element
s = {10, 20, 30}
x = s.pop()
print(x)
print(s)
6️⃣ clear() — Remove all elements
s = {1, 2, 3}
s.clear()
print(s) # set()
🧮 Mathematical Set Operations
7️⃣ union() — Combine sets
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
8️⃣ intersection() — Common elements
a = {1, 2, 3}
b = {2, 3, 4}
print(a.intersection(b)) # {2, 3}
9️⃣ difference() — Elements in A but not in B
a = {1, 2, 3}
b = {2, 3}
print(a.difference(b)) # {1}
🔟 symmetric_difference() — Unique elements from both sets
(Excludes common items)
a = {1, 2, 3}
b = {3, 4}
print(a.symmetric_difference(b)) # {1, 2, 4}
🧾 Other useful methods
11️⃣ issubset()
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b)) # True
12️⃣ issuperset()
b.issuperset(a) # True
13️⃣ isdisjoint()
{1, 2}.isdisjoint({3, 4}) # True
🎯 Summary Table
Method Description
add() Add single element
update() Add multiple elements
remove() Remove element (error if missing)
discard() Remove element (no error)
pop() Remove random element
clear() Empty the set
union() Combine sets
intersection() Common elements
difference() A - B
symmetric_difference() Items not common
issubset() A inside B
issuperset() A covers B
isdisjoint() No common elements
Информация по комментариям в разработке