LEARN COMPLETE PYTHON IN 24 HOURS
11. Sets
A set is an unordered, mutable collection of unique items (no duplicates allowed). Sets are very fast for checking if an item exists (in operator) and for performing mathematical operations like union, intersection, etc.
11.1 What is a Set? Unique Values
Key Features of Sets:
Unordered → No indexing (cannot use [0], [1], etc.)
No duplicates → Adding the same item multiple times has no effect
Mutable → You can add/remove items (but items themselves must be immutable: numbers, strings, tuples — not lists or dictionaries)
Very fast membership testing (in is O(1) average time)
Creating a Set:
Using curly braces {}
Python
fruits = {"apple", "banana", "mango", "apple"} # duplicate "apple" ignored print(fruits) # {'apple', 'banana', 'mango'} (order may vary)
Using set() function
Python
empty_set = set() # Important! {} is empty dict, not empty set numbers = set([1, 2, 2, 3, 4]) # {1, 2, 3, 4} from_string = set("hello") # {'h', 'e', 'l', 'o'} (unique characters)
Remove duplicates from a list (very common use)
Python
my_list = [10, 20, 10, 30, 20, 40] unique = set(my_list) print(unique) # {10, 20, 30, 40}
Check membership
Python
print("apple" in fruits) # True print("grape" in fruits) # False
Tip: Use sets when order doesn't matter and duplicates are unwanted (e.g., unique users, tags, IDs).
11.2 Set Operations (union, intersection, difference, symmetric difference)
Sets support mathematical operations — very useful in data analysis, filtering, etc.
OperationSymbolMethodDescriptionExample (A = {1,2,3}, B = {3,4,5})Union``A.union(B)All elements from both setsIntersection&A.intersection(B)Elements common to both{3}Difference-A.difference(B)Elements in A but not in B{1,2}Symmetric Difference^A.symmetric_difference(B)Elements in A or B but not both{1,2,4,5}
Examples with code:
Python
A = {1, 2, 3, 4} B = {3, 4, 5, 6} # Union print(A | B) # {1, 2, 3, 4, 5, 6} print(A.union(B)) # same # Intersection print(A & B) # {3, 4} print(A.intersection(B)) # same # Difference print(A - B) # {1, 2} print(B - A) # {5, 6} # Symmetric Difference print(A ^ B) # {1, 2, 5, 6} print(A.symmetric_difference(B)) # same
Real-life Example – Find common friends
Python
my_friends = {"Rahul", "Priya", "Ankit", "Sneha"} her_friends = {"Sneha", "Vikram", "Priya", "Rohan"} common = my_friends & her_friends print("Common friends:", common) # {'Priya', 'Sneha'} only_mine = my_friends - her_friends print("Only my friends:", only_mine) # {'Rahul', 'Ankit'}
Tip: You can chain operations: A | B & C - D
11.3 Set Methods (add, remove, discard, update, etc.)
Sets have useful methods for modification.
MethodDescriptionExampleEffect / Returnsadd(item)Add a single items.add(10)Adds if not presentupdate(iterable)Add multiple items from list/tuple/sets.update([5,6,7])Adds all unique itemsremove(item)Remove item (raises KeyError if missing)s.remove(3)Removes itemdiscard(item)Remove item (no error if missing)s.discard(99)Safe removepop()Remove & return arbitrary items.pop()Returns removed itemclear()Remove all itemss.clear()Becomes empty setcopy()Shallow copynew = s.copy()Independent copyissubset()Check if all elements are in another setA.issubset(B)True/Falseissuperset()Check if contains another setB.issuperset(A)True/Falseisdisjoint()No common elementsA.isdisjoint(B)True/False
Practical Examples:
Python
s = {1, 2, 3} s.add(4) # {1, 2, 3, 4} s.update([3, 5, 6, 4]) # {1, 2, 3, 4, 5, 6} (duplicates ignored) s.remove(2) # {1, 3, 4, 5, 6} s.discard(99) # No error print(s.pop()) # Removes random item, e.g., 1 print(s) # e.g. {3, 4, 5, 6} # Set relations A = {1, 2, 3} B = {1, 2, 3, 4} print(A.issubset(B)) # True print(B.issuperset(A)) # True print(A.isdisjoint({5,6})) # True
Mini Project – Unique Visitors & Common Interests
Python
visitors_today = ["user1", "user2", "user1", "user3", "user4"] unique_visitors = set(visitors_today) print("Unique visitors today:", len(unique_visitors), unique_visitors) # Interests group_A = {"cricket", "coding", "music", "football"} group_B = {"coding", "reading", "music", "chess"} print("Common interests:", group_A & group_B) # {'coding', 'music'} print("All interests:", group_A | group_B) print("Only group A:", group_A - group_B)
This completes the full Sets section — short, powerful, and super useful for uniqueness and operations!
Email-ibm.anshuman@gmail.com
© 2026 CodeForge AI | Privacy Policy |Terms of Service | Contact | Disclaimer | 1000 university college list|book library australia 2026
All my books are exclusively available on Amazon. The free notes/materials on globalcodemaster.com do NOT match even 1% with any of my PUBLISHED BOoks. Similar topics ≠ same content. Books have full details, exercises, chapters & structure — website notes do not.No book content is shared here. We fully comply with Amazon policies.