Python Notes
HubHistory of Python - Complete Guide 2026Python Applications - Complete Guide 2026Python Features - Complete Guide 2026What is Python? - Complete Guide 2026Why Learn Python? - Complete Guide 2026Your First Python Program – Hello World & Beyond 2026How to Install Python on Windows, Mac & Linux – Complete Guide 2026Install VS Code for Python – Complete Setup Guide with Extensions 2026Python Environment Setup – Virtual Environments, pip & Project Structure 2026Python IDLE – Complete Guide for Beginners 2026Python CommentsPython Data TypesPython Input and OutputPython OperatorsPython SyntaxPython Strings BasicsPython Type CastingPython VariablesBreak, Continue and Pass in PythonElif Statement in PythonFor Loop in PythonIf-Else Statement in PythonIf Statement in PythonNested If in PythonPattern Programs in PythonWhile Loop in PythonDecorators in PythonFunction Arguments in PythonFunctions Basics in PythonGenerators in PythonLambda Functions in PythonRecursive Functions in PythonReturn Statement in PythonScope of Variables in PythonAbstraction in PythonClasses and Objects in PythonConstructors in PythonEncapsulation in PythonInheritance in PythonMagic Methods (Dunder Methods) in PythonMethod Overriding in PythonPolymorphism in PythonPython Comprehensions – List, Dict, Set & GeneratorPython Dictionaries – Key-Value StorePython Dictionary Methods – Complete ReferencePython List Methods – All Built-in MethodsPython Lists – Complete GuidePython Set Methods – Complete ReferencePython Sets – Unordered Unique CollectionsPython Tuples – Immutable SequencesPython Asynchronous Programming with asyncioPython Context ManagersAdvanced Python DecoratorsAdvanced Python GeneratorsPython Iterators - Advanced GuidePython Memory ManagementPython MultiprocessingPython MultithreadingCRUD Operations in Python DatabasesMySQL with Python (mysql-connector-python)ORM Introduction with SQLAlchemyPostgreSQL with Python (psycopg2)SQLite3 with PythonIntroduction to DjangoDjango Models and ORMDjango REST API with DRFDjango ViewsIntroduction to FlaskFlask RoutingFlask Templates with Jinja2Email Automation with PythonPDF Automation with PythonSelenium Web Automation with PythonTask Scheduler with PythonWeb Scraping with PythonData Analysis with PythonData Cleaning with PythonData Visualization ProjectData Visualization with MatplotlibNumPy IntroductionPandas IntroductionStatistical Visualization with SeabornClassification AlgorithmsClustering AlgorithmsIntroduction to Machine LearningMachine Learning Project: Churn PredictionModel Evaluation and SelectionRegression AlgorithmsSave pipeline (includes preprocessing + model)AI Assistant ProjectCalculator ProjectChatbot ProjectExpense Tracker ProjectFace Detection ProjectPassword Generator ProjectWeather App ProjectPython Coding Interview QuestionsPython OOP Interview Questions and AnswersPython Master CheatsheetPython Interview Questions and AnswersPython Best PracticesCommon Python Errors and SolutionsPython Debugging TechniquesPython Learning Resources
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
Set A = {1, 2, 3, 4} Set B = {3, 4, 5, 6}
Union (A | B): Intersection (A & B):
{1, 2, 3, 4, 5, 6} {3, 4}
Difference (A - B): Symmetric Difference (A ^ B):
{1, 2} {1, 2, 5, 6}
┌───────────────────────────────────┐
│ A B │
│ ┌──────┐ ┌──────┐ │
│ │ 1 2 │ │ 5 6 │ │
│ │ ┌─┴───┴─┐ │ │
│ │ │ 3 4 │ │ │
│ └────┴─┬───┬─┘────┘ │
│ └───┘ │
└───────────────────────────────────┘
python example
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
python example
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:
Example
True
False
True
True
True
False
True
True
True
False
True
False
4. Membership Test (O(1) – बहुत Fast!)
python example
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
python example
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
Example
# Create frozenset
fs = frozenset([1, 2, 3, 4, 5])
fs2 = frozenset("hello")
print(fs) # frozenset({1, 2, 3, 4, 5})
print(fs2) # frozenset({'h', 'e', 'l', 'o'})
# frozenset supports all read operations
print(3 in fs) # True
print(len(fs)) # 5
print(fs | {6, 7}) # frozenset({1, 2, 3, 4, 5, 6, 7})
# ❌ Cannot modify
try:
fs.add(6)
except AttributeError as e:
print(f"Error: {e}") # 'frozenset' has no 'add'
# ✅ frozenset as dictionary key (regular set cannot!)
d = {frozenset([1, 2]): "pair", frozenset([3, 4]): "another"}
print(d[frozenset([1, 2])]) # pair
# ✅ frozenset as set element
s = {frozenset([1, 2]), frozenset([3, 4])}
print(s) # {frozenset({1, 2}), frozenset({3, 4})}
Output:
Example
frozenset({1, 2, 3, 4, 5})
frozenset({'h', 'e', 'l', 'o'})
True
5
frozenset({1, 2, 3, 4, 5, 6, 7})
Error: 'frozenset' object has no attribute 'add'
pair
{frozenset({1, 2}), frozenset({3, 4})}
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 (असली उपयोग)
Example
# 1. Remove duplicates from list (order preserved in 3.7+)
names = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Dave"]
unique_names = list(dict.fromkeys(names)) # order preserved
print(unique_names) # ['Alice', 'Bob', 'Charlie', 'Dave']
# Quick but unordered:
unique_set = list(set(names))
print(sorted(unique_set)) # ['Alice', 'Bob', 'Charlie', 'Dave']
# 2. Common elements between two lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common = list(set(list1) & set(list2))
print(common) # [3, 4, 5]
# 3. Unique visitors to a website
visitors = set()
visitors.add("user1")
visitors.add("user2")
visitors.add("user1") # duplicate – ignored
visitors.add("user3")
print(f"Unique visitors: {len(visitors)}") # 3
# 4. Tags/categories
article_tags = {"python", "programming", "tutorial"}
user_interests = {"python", "machine-learning", "tutorial"}
matching_tags = article_tags & user_interests
print("Matching tags:", matching_tags) # {'python', 'tutorial'}
# 5. Graph – visited nodes
def bfs(graph, start):
visited = set()
queue = [start]
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
queue.extend(graph.get(node, []))
return visited
graph = {1: [2, 3], 2: [4], 3: [4, 5], 4: [], 5: []}
print(bfs(graph, 1)) # {1, 2, 3, 4, 5}
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 तरीका?
Example
nums = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(nums)) # O(n), order not preserved
unique_ordered = list(dict.fromkeys(nums)) # order preserved
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?
Example
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
sym_diff = list(set(a) ^ set(b))
print(sym_diff) # [1, 2, 5, 6]
Q5: Check करें कि दो lists में exactly same unique elements हैं?
Example
a = [1, 2, 2, 3]
b = [3, 1, 2]
print(set(a) == set(b)) # True
Summary
Example
# Set creation
s = {1, 2, 3}
s = set([1, 2, 2, 3]) # duplicates removed
s = set() # empty set
# Operations
A | B # union
A & B # intersection
A - B # difference
A ^ B # symmetric difference
A <= B # subset
A >= B # superset
# Frozenset (immutable)
fs = frozenset([1, 2, 3])
Output Blocks for Remaining Code Examples
Section 4 – Membership Test Output:
Output
List: 0.0156s Set: 0.0002s True False
Section 5 – Set Iteration Output:
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:
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 करना
python example
# ❌ WRONG – यह dict बनाता है!
empty = {}
print(type(empty)) # <class 'dict'>
# ✅ CORRECT – set() use करें
empty = set()
print(type(empty)) # <class 'set'>Output
<class 'dict'> <class 'set'>
❌ Mistake 2: Set में mutable elements add करना
Example
# ❌ WRONG – List is unhashable
try:
s = {[1, 2], [3, 4]}
except TypeError as e:
print(f"Error: {e}")
# ✅ CORRECT – Tuple use करें (immutable & hashable)
s = {(1, 2), (3, 4)}
print(s)
Output
Error: unhashable type: 'list'
{(1, 2), (3, 4)}❌ Mistake 3: Set से indexing try करना
Example
# ❌ WRONG – Set is unordered, no indexing!
s = {10, 20, 30}
try:
print(s[0])
except TypeError as e:
print(f"Error: {e}")
# ✅ CORRECT – Convert to list first
print(list(s)[0])
Output
Error: 'set' object is not subscriptable 10
❌ Mistake 4: remove() use करना बिना check किए
python example
# ❌ 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}Output
KeyError: 99
{1, 2, 3}❌ Mistake 5: Set order पर rely करना
Example
# ❌ WRONG – Set unordered है, order guarantee नहीं!
s = {"banana", "apple", "cherry"}
# हर बार output अलग आ सकता है
print(s) # Could be {'cherry', 'banana', 'apple'}
# ✅ CORRECT – sorted() use करें for guaranteed order
print(sorted(s)) # ['apple', 'banana', 'cherry']
Output
{'cherry', 'banana', 'apple'}
['apple', 'banana', 'cherry']❌ Mistake 6: True और 1 को different elements मानना
python example
# Python में True == 1 और False == 0
s = {True, 1, False, 0}
print(s) # {True, False} या {0, 1}
print(len(s)) # 2 (not 4!)Output
{False, True}
2❌ Mistake 7: Set comprehension vs Dict comprehension confusion
python example
# 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, ...}Output
<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 कैसे निकालें?
python example
# 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 setsOutput
Common elements: 50000
IQ3: Set comprehension और Generator expression में difference?
python example
# 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))Output
<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 करें?
Example
nested = [[1, 2], [2, 3], [3, 4], [1, 2]]
# Convert inner lists to tuples (hashable) then to set
unique = set(tuple(item) for item in nested)
result = [list(item) for item in unique]
print(result) # [[1, 2], [2, 3], [3, 4]]
Output
[[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 करें?
python example
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))Output
{Student(Alice, 1), Student(Bob, 2)}
2IQ7: Find pairs in array whose sum equals target — using set approach?
Example
def find_pairs(arr, target):
seen = set()
pairs = []
for num in arr:
complement = target - num
if complement in seen:
pairs.append((complement, num))
seen.add(num)
return pairs
result = find_pairs([2, 4, 3, 7, 1, 8, 5], 9)
print(result) # [(2, 7), (4, 5), (1, 8)]
# Time: O(n), Space: O(n)
Output
[(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?
Example
def longest_consecutive(nums):
num_set = set(nums)
longest = 0
for num in num_set:
# Only start counting from beginning of sequence
if num - 1 not in num_set:
current = num
streak = 1
while current + 1 in num_set:
current += 1
streak += 1
longest = max(longest, streak)
return longest
print(longest_consecutive([100, 4, 200, 1, 3, 2])) # 4 (1→2→3→4)
print(longest_consecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1])) # 9 (0→8)
# Time: O(n), Space: O(n)
Output
4 9
IQ10: Power Set (सभी subsets) generate करें using sets?
Example
from itertools import combinations
def power_set(s):
s = list(s)
result = [set()]
for r in range(1, len(s) + 1):
for combo in combinations(s, r):
result.append(set(combo))
return result
original = {1, 2, 3}
ps = power_set(original)
print(f"Original: {original}")
print(f"Power set size: {len(ps)}") # 2^n = 8
for subset in ps:
print(subset)
Output
Original: {1, 2, 3}
Power set size: 8
set()
{1}
{2}
{3}
{1, 2}
{1, 3}
{2, 3}
{1, 2, 3}Continue the lesson path
Study next in this module
01Data StructuresPython Set Methods – Complete ReferencePython Set के सभी built-in methods का complete reference – add, remove, discard, pop, clear, update, union, intersection, difference, symmetric_difference और in-place variants के साथ examples।02Data StructuresPython Tuples – Immutable SequencesPython Tuples का complete guide – immutability, creation, packing/unpacking, named tuples, tuple vs list comparison, use cases, और interview questions हिंदी में।03Data StructuresPython Lists – Complete GuidePython Lists ka complete guide – creation, indexing, slicing, mutability, nesting, and real-world usage with code examples, time complexity, and interview questions.04Data StructuresPython List Methods – All Built-in MethodsPython List के सभी built-in methods का complete reference – append, extend, insert, remove, pop, sort, reverse, index, count, copy, clear – examples और time complexity के साथ।