Set Basics
Learn sets from scratch: uniqueness, fast membership checks, and practical use cases like removing duplicates and comparing groups of data.
A **set** stores **unique items** and is usually **unordered**. ### Why sets matter Sets are extremely useful when you want: - remove duplicates - check membership fast - compare groups (common vs missing) ## Create a set ```python nums = {1, 2, 3, 3, 3} print(nums) # {1,2,3} duplicates removed ``` ## Add and remove ```python s = {"a", "b"} s.add("c") s.remove("b") # error if missing s.discard("x") # safe if missing ``` ## Fast membership ```python users = {"Tom", "Sarah", "Mike"} print("Sarah" in users) # fast ``` ## Common set operations (very useful) ```python a = {"Tom", "Sarah", "Mike"} b = {"Sarah", "Ahsan"} print(a & b) # intersection -> common print(a | b) # union -> all print(a - b) # difference -> in a not in b ``` ## Real example: find new applicants ```python applied = {"Tom", "Sarah"} all_users = {"Tom", "Sarah", "Mike", "Ahsan"} not_applied = all_users - applied print(not_applied) ``` ## Graph: set uniqueness ```mermaid flowchart LR A[Input: a,a,b,c] --> B[Set] B --> C[Output: a,b,c] ``` ## Remember - Sets remove duplicates automatically - Use sets for fast membership - Set operations solve many real problems