Python Notes
Python Sets का complete guide – creation, operations, set theory (union, intersection, difference), frozen sets, और real-world use cases with Hindi explanations और interview questions.
Introduction (परिचय)
Set एक unordered collection है जिसमें unique elements होते हैं। Mathematical sets की तरह – union, intersection, difference operations supported हैं।
Key Properties: - ❌ Unordered – Elements का कोई fixed order नहीं - ✅ Unique – Duplicate elements automatically remove हो जाते हैं - ✅ Mutable – Elements add/remove किए जा सकते हैं - ✅ Hashable Elements Only – Lists, dicts set में नहीं जा सकते - ⚡ O(1) Lookup – membership test बहुत fast
2. Set Operations – Mathematical Operations
Visual Diagram
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
# Union – दोनों sets के सभी elements
print(A | B) # {1, 2, 3, 4, 5, 6}
print(A.union(B)) # {1, 2, 3, 4, 5, 6}
# Intersection – दोनों में common elements
print(A & B) # {3, 4}
print(A.intersection(B)) # {3, 4}
# Difference – A में हैं, B में नहीं
print(A - B) # {1, 2}
print(A.difference(B)) # {1, 2}
print(B - A) # {5, 6}
# Symmetric Difference – किसी एक में हैं, दोनों में नहीं
print(A ^ B) # {1, 2, 5, 6}
print(A.symmetric_difference(B)) # {1, 2, 5, 6}
# Multiple sets union
C = {5, 6, 7, 8}
print(A | B | C) # {1, 2, 3, 4, 5, 6, 7, 8}
print(A.union(B, C)) # {1, 2, 3, 4, 5, 6, 7, 8}Output:
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
{3, 4}
{3, 4}
{1, 2}
{1, 2}
{5, 6}
{1, 2, 5, 6}
{1, 2, 5, 6}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}
3. Set Comparison Operations
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {1, 2, 3}
D = {10, 20}
# Equality
print(A == C) # True (same elements)
print(A == B) # False
# Subset (A ⊆ B) – A के सभी elements B में हैं?
print(A <= B) # True (A is subset of B)
print(A.issubset(B)) # True
# Proper subset (A ⊂ B) – A subset है और A ≠ B
print(A < B) # True (A is proper subset of B)
print(A < C) # False (A == C, not proper)
# Superset (B ⊇ A)
print(B >= A) # True (B is superset of A)
print(B.issuperset(A)) # True
# Proper superset
print(B > A) # True
print(A > C) # False
# Disjoint – no common elements
print(A.isdisjoint(D)) # True (A ∩ D = ∅)
print(A.isdisjoint(B)) # False (common elements exist)Output:
4. Membership Test (O(1) – बहुत Fast!)
big_list = list(range(1_000_000))
big_set = set(range(1_000_000))
import timeit
# List membership: O(n) – slow
list_time = timeit.timeit(
"999_999 in big_list",
globals={"big_list": big_list},
number=1000
)
# Set membership: O(1) – fast
set_time = timeit.timeit(
"999_999 in big_set",
globals={"big_set": big_set},
number=1000
)
print(f"List: {list_time:.4f}s") # ~20x slower
print(f"Set: {set_time:.4f}s") # ~instant
# Practical example
spam_words = {"free", "winner", "click", "discount", "prize"}
def is_spam(message):
words = message.lower().split()
return any(word in spam_words for word in words)
print(is_spam("You are a winner! Click here for free prize!")) # True
print(is_spam("Hello, how are you today?")) # False5. Set Iteration
fruits = {"apple", "banana", "cherry", "date"}
# Basic iteration (order not guaranteed)
for fruit in fruits:
print(fruit)
# Sorted iteration
for fruit in sorted(fruits):
print(fruit)
# Enumerate (index added, but order not guaranteed)
for i, fruit in enumerate(sorted(fruits)):
print(f"{i}: {fruit}")
# Set comprehension
squares = {x**2 for x in range(1, 6)}
print(squares) # {1, 4, 9, 16, 25}
# Conditional set comprehension
even_squares = {x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares) # {4, 16, 36, 64, 100}6. Frozenset – Immutable Set
Output:
7. Time Complexity
| Operation | Average | Worst | Notes | |
|---|---|---|---|---|
x in s | O(1) | O(n) | Hash lookup | |
s.add(x) | O(1) | O(n) | Occasional rehash | |
s.remove(x) | O(1) | O(n) | ||
s.discard(x) | O(1) | O(n) | No error if missing | |
len(s) | O(1) | O(1) | Stored attribute | |
| `s \ | t` (union) | O(len(s)+len(t)) | ||
s & t (intersection) | O(min(len(s),len(t))) | |||
s - t (difference) | O(len(s)) | |||
s <= t (subset) | O(len(s)) |
8. Real-World Examples (असली उपयोग)
9. Set vs List vs Tuple vs Dict
| Feature | Set | List | Tuple | Dict |
|---|---|---|---|---|
| Ordered | ❌ No | ✅ Yes | ✅ Yes | ✅ Yes (3.7+) |
| Duplicates | ❌ No | ✅ Yes | ✅ Yes | Keys: ❌ |
| Mutable | ✅ Yes | ✅ Yes | ❌ No | ✅ Yes |
| Indexing | ❌ No | ✅ Yes | ✅ Yes | Key-based |
| Membership | O(1) | O(n) | O(n) | O(1) |
| Memory | Medium | Medium | Less | More |
| Use case | Unique items | Sequence | Fixed seq | Key-value |
10. Interview Questions
Q1: List से duplicates remove करने का सबसे fast तरीका?
Q2: Set में {} empty set क्यों नहीं create करता?
Python में{}एक empty dict बनाता है, क्योंकि dict Python में set से पहले introduce हुई थी। Empty set के लिए हमेशाset()use करें।
Q3: Set में list क्यों नहीं जा सकती?
Set के elements hashable होने चाहिए (unique hash value)। List mutable है इसलिए unhashable है। Tuple (immutable) set में जा सकती है।
Q4: Two lists के बीच symmetric difference?
Q5: Check करें कि दो lists में exactly same unique elements हैं?
Summary
Output Blocks for Remaining Code Examples
Section 4 – Membership Test Output:
List: 0.0156s Set: 0.0002s True False
Section 5 – Set Iteration Output:
apple
banana
cherry
date
apple
banana
cherry
date
0: apple
1: banana
2: cherry
3: date
{1, 4, 9, 16, 25}
{64, 4, 36, 100, 16}Section 8 – Real-World Examples Output:
['Alice', 'Bob', 'Charlie', 'Dave']
['Alice', 'Bob', 'Charlie', 'Dave']
[3, 4, 5]
Unique visitors: 3
Matching tags: {'python', 'tutorial'}
{1, 2, 3, 4, 5}⚠️ Common Mistakes (आम गलतियाँ)
❌ Mistake 1: Empty set बनाने में {} use करना
# ❌ WRONG – यह dict बनाता है!
empty = {}
print(type(empty)) # <class 'dict'>
# ✅ CORRECT – set() use करें
empty = set()
print(type(empty)) # <class 'set'><class 'dict'> <class 'set'>
❌ Mistake 2: Set में mutable elements add करना
Error: unhashable type: 'list'
{(1, 2), (3, 4)}❌ Mistake 3: Set से indexing try करना
Error: 'set' object is not subscriptable 10
❌ Mistake 4: remove() use करना बिना check किए
# ❌ WRONG – KeyError अगर element नहीं है
s = {1, 2, 3}
try:
s.remove(99)
except KeyError as e:
print(f"KeyError: {e}")
# ✅ CORRECT – discard() use करें (no error if missing)
s.discard(99)
print(s) # {1, 2, 3}KeyError: 99
{1, 2, 3}❌ Mistake 5: Set order पर rely करना
{'cherry', 'banana', 'apple'}
['apple', 'banana', 'cherry']❌ Mistake 6: True और 1 को different elements मानना
# Python में True == 1 और False == 0
s = {True, 1, False, 0}
print(s) # {True, False} या {0, 1}
print(len(s)) # 2 (not 4!){False, True}
2❌ Mistake 7: Set comprehension vs Dict comprehension confusion
# Set comprehension
s = {x for x in range(5)}
print(type(s), s) # <class 'set'> {0, 1, 2, 3, 4}
# ❌ Confusion – यह dict comprehension है!
d = {x: x**2 for x in range(5)}
print(type(d), d) # <class 'dict'> {0: 0, 1: 1, ...}<class 'set'> {0, 1, 2, 3, 4}
<class 'dict'> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}✅ Key Takeaways (मुख्य बातें)
- 🔹 Set = Unordered + Unique: Set में कोई duplicate element नहीं रहता, और order guaranteed नहीं होता।
- 🔹 Empty set बनाने के लिए
set()use करें:{}empty dict बनाता है, empty set नहीं! - 🔹 O(1) Membership Test:
inoperator sets में O(1) time में काम करता है — lists की O(n) से बहुत fast है। - 🔹 Only Hashable Elements: Set में सिर्फ immutable (hashable) elements जा सकते हैं — list, dict नहीं जा सकते।
- 🔹 Mathematical Operations: Union (
|), Intersection (&), Difference (-), Symmetric Difference (^) — सब supported हैं। - 🔹
discard()>remove():discard()element missing होने पर error नहीं देता,remove()KeyError raise करता है। - 🔹 Frozenset = Immutable Set: जब set को dict key या set element बनाना हो तो frozenset use करें।
- 🔹 Duplicates Remove करने का fastest तरीका:
list(set(data))— O(n) time complexity। - 🔹 Set Comprehension:
{x**2 for x in range(10)}— concise और readable syntax for building sets। - 🔹 Real-World Uses: Spam filtering, unique visitors tracking, graph traversal (visited nodes), tag matching — sets हर जगह काम आते हैं!
❓ FAQ (अक्सर पूछे जाने वाले सवाल)
Q1: Set और List में main difference क्या है?
Answer: List ordered होती है और duplicates allow करती है। Set unordered होता है और सिर्फ unique elements रखता है। List में indexing (list[0]) possible है, Set में नहीं। Set में membership test O(1) है जबकि List में O(n)।Q2: Set में order preserve क्यों नहीं होता?
Answer: Set internally hash table use करता है। Elements hash value के basis पर store होते हैं, insertion order के basis पर नहीं। इसलिए guaranteed order नहीं मिलता। अगर order चाहिए तोsorted()use करें याdict.fromkeys()method use करें।
Q3: Frozenset कब use करना चाहिए?
Answer: जब आपको immutable set चाहिए — जैसे dictionary key बनाना हो, किसी set के अंदर set रखना हो, या function argument के रूप में unchangeable collection pass करना हो। Frozenset hashable होता है इसलिए dict key बन सकता है।
Q4: Set में maximum कितने elements रख सकते हैं?
Answer: Python sets की कोई fixed limit नहीं है — यह available memory पर depend करता है। Practically millions of elements store कर सकते हैं, लेकिन बहुत large sets memory intensive होते हैं।
Q5: add() और update() में क्या difference है?
Answer:add()single element add करता है:s.add(5)।update()multiple elements (iterable) add करता है:s.update([5, 6, 7])।update()internally iterate करके सब elements एक-एक करके add करता है।
Q6: Set को sort कैसे करें?
Answer: Set को directly sort नहीं कर सकते (unordered है)। sorted(my_set) use करें — यह एक sorted list return करता है। Set sorted state maintain नहीं करता, हर बार sorted() call करना पड़ता है।Q7: set() constructor में कौन-कौन से iterables pass कर सकते हैं?
Answer: कोई भी iterable — list, tuple, string, range, dictionary (keys), generator expression, दूसरा set। Example:set("hello")→{'h', 'e', 'l', 'o'},set(range(5))→{0, 1, 2, 3, 4}।
Q8: Set operations (|, &, -) और methods (.union(), .intersection()) में difference?
Answer: Operators (|,&) दोनों sides पर set type require करते हैं। Methods (.union(),.intersection()) कोई भी iterable accept करते हैं right-hand side पर। Example:{1,2}.union([3,4])✅ works, लेकिन{1,2} | [3,4]❌ TypeError देगा।
🎯 Interview Questions (विस्तृत उत्तर)
IQ1: Set internally कैसे काम करता है? (Internal Implementation)
Answer: Python set internally hash table use करता है। जब कोई element add होता है तो उसका hash compute होता है, और उस hash के basis पर memory location decide होती है। Collision handling open addressing (linear probing) से होता है। इसीलिए lookup O(1) average time में होता है।
IQ2: दो large lists का intersection efficiently कैसे निकालें?
# Method 1: Set intersection (Recommended)
list1 = list(range(100000))
list2 = list(range(50000, 150000))
common = list(set(list1) & set(list2))
print(f"Common elements: {len(common)}") # 50000
# Time Complexity: O(n + m) where n, m = list lengths
# Space Complexity: O(n + m) for creating setsCommon elements: 50000
IQ3: Set comprehension और Generator expression में difference?
# Set comprehension → returns set
s = {x**2 for x in range(10)}
print(type(s), s)
# Generator expression → returns generator (lazy evaluation)
g = (x**2 for x in range(10))
print(type(g), list(g))<class 'set'> {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
<class 'generator'> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]IQ4: Nested list से unique elements कैसे extract करें?
[[1, 2], [2, 3], [3, 4]]
IQ5: set() vs frozenset() — कब कौन use करें?
Answer:set()use करें जब elements add/remove करने हों (mutable operations)।frozenset()use करें जब set को hashable बनाना हो — dict key, set of sets, या constant data represent करना हो। frozenset thread-safe भी consider किया जा सकता है (immutable)।
IQ6: Set में custom objects कैसे store करें?
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
def __hash__(self):
return hash((self.name, self.roll))
def __eq__(self, other):
return self.name == other.name and self.roll == other.roll
def __repr__(self):
return f"Student({self.name}, {self.roll})"
students = {Student("Alice", 1), Student("Bob", 2), Student("Alice", 1)}
print(students) # Duplicate Alice removed!
print(len(students)){Student(Alice, 1), Student(Bob, 2)}
2IQ7: Find pairs in array whose sum equals target — using set approach?
[(2, 7), (4, 5), (1, 8)]
IQ8: Set operations का time complexity compare करें List operations से?
Answer: | Operation | Set | List | |-----------|-----|------| | Membership (in) | O(1) avg | O(n) | | Add element | O(1) avg | O(1) amortized (append) | | Remove element | O(1) avg | O(n) | | Union/Combine | O(n+m) | O(n+m) | | Intersection | O(min(n,m)) | O(n*m) naive | Set हमेशा fast है membership और remove operations के लिए।IQ9: Write a function to find longest consecutive sequence using Set?
4 9
IQ10: Power Set (सभी subsets) generate करें using sets?
Original: {1, 2, 3}
Power set size: 8
set()
{1}
{2}
{3}
{1, 2}
{1, 3}
{2, 3}
{1, 2, 3}Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Sets – Unordered Unique Collections.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, data, structures, sets
Related Python Master Course Topics