SET
Definition:
A set is an unordered collection of unique elements in Python, written using curly braces {}.
🔹 Key Points
Elements are unordered
Duplicate values are not allowed
Sets are mutable (elements can be added or removed)
Sets do not support indexing or slicing
🔹 Example
s = {10, 20, 30, 20}
print(s)
Output:
{10, 20, 30}
(Duplicate value 20 is removed)
🔹 Difference Between List and Tuple
Feature List Tuple
Brackets [] ()
Mutable Yes No
Speed Slower Faster
SET OPERATORS (with data & example)
1️⃣ Union (|)
Meaning: Combines elements from both sets (no duplicates)
Data:
A = {1, 2, 3}
B = {3, 4, 5}
Example:
print(A | B)
Output:
{1, 2, 3, 4, 5}
2️⃣ Intersection (&)
Meaning: Common elements in both sets
print(A & B)
Output:
{3}
3️⃣ Difference (-)
Meaning: Elements present in first set but not in second
print(A - B)
Output:
{1, 2}
4️⃣ Symmetric Difference (^)
Meaning: Elements present in either set but not in both
print(A ^ B)
Output:
{1, 2, 4, 5}
5️⃣ Membership (in, not in)
print(2 in A)
print(6 not in A)
Output:
True
True
SET METHODS (with data & example)
add()
Adds one element
s = {1, 2}
[Link](3)
print(s)
Output:
{1, 2, 3}
2️⃣ update()
Adds multiple elements
[Link]([4, 5])
print(s)
Output:
{1, 2, 3, 4, 5}
3️⃣ remove()
Removes an element (error if not found)
[Link](2)
print(s)
Output:
{1, 3, 4, 5}
4️⃣ discard()
Removes element (no error if missing)
[Link](10)
print(s)
Output:
{1, 3, 4, 5}
5️⃣ pop()
Removes a random element
[Link]()
print(s)
Output (example):
{3, 4, 5}
6️⃣ clear()
Removes all elements
[Link]()
print(s)
Output:
set()
7️⃣ union()
print([Link](B))
Output:
{1, 2, 3, 4, 5}
8️⃣ intersection()
print([Link](B))
Output:
{3}
9️⃣ difference()
print([Link](B))
Output:
{1, 2}
🔟 issubset() / issuperset()
X = {1, 2}
Y = {1, 2, 3}
print([Link](Y))
print([Link](X))
Output:
True
True
Tasks1:Write a Python program to perform the following operations:
1. Find and display the union of set A and set B.
2. Find and display the intersection of set A and set B.
3. Find and display the symmetric difference between set A and set B.
4. Check whether the element 20 is present in the union set and display the result.
Source code:
A = {10, 20, 30, 40}
B = {30, 40, 50, 60}
union_set = A | B
intersection_set = A & B
symmetric_diff = A ^ B
print("Union:", union_set)
print("Intersection:", intersection_set)
print("Symmetric Difference:", symmetric_diff)
print("Is 20 present in Union?", 20 in union_set)
✅ Output
mathematica
Copy code
Union: {10, 20, 30, 40, 50, 60}
Intersection: {30, 40}
Symmetric Difference: {10, 20, 50, 60}
Is 20 present in Union? True