Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟢 Beginner  ·  Lesson 16

List, Set और Dictionary Comprehension

Comprehension क्या है?

Comprehension मौजूदा data से एक पढ़ने में आसान line में नई list, set या dictionary बनाता है। यह आम pattern “ख़ाली list बनाओ → loop → append” की जगह लेता है।

Python – loop_vs_comprehension.py
prices = [120, 450, 80, 999]

# normal loop
with_gst = []
for p in prices:
    with_gst.append(round(p * 1.18))
print(with_gst)

# list comprehension – same result
with_gst = [round(p * 1.18) for p in prices]
print(with_gst)
[142, 531, 94, 1179] [142, 531, 94, 1179]

इसे ऐसे पढ़ें: [ expression for item in iterable if condition ] → “iterable के हर उस item के लिए expression बनाओ जो condition पास करे”।

if से filter करना

Python – filter.py
marks = {"Asha": 91, "Ravi": 58, "Neha": 76, "Kabir": 34, "Isha": 88}

passed = [name for name, m in marks.items() if m >= 40]
toppers = [name for name, m in marks.items() if m >= 85]
print("Passed :", passed)
print("Toppers:", toppers)
Passed : ['Asha', 'Ravi', 'Neha', 'Isha'] Toppers: ['Asha', 'Isha']

Expression के अंदर if-else

Filter नहीं, बल्कि दो values में से चुनने के लिए if … else … को for से पहले लिखें।

Python – if_else.py
marks = [91, 58, 76, 34, 88]

result = ["Pass" if m >= 40 else "Fail" for m in marks]
grades = ["A" if m >= 85 else "B" if m >= 60 else "C" if m >= 40 else "F" for m in marks]
print(result)
print(grades)
['Pass', 'Pass', 'Pass', 'Fail', 'Pass'] ['A', 'C', 'B', 'F', 'A']
स्थानउद्देश्यउदाहरण
for के बाद ifकुछ items ही रखें (filter)[m for m in marks if m >= 40]
for से पहले if … elseहर item को दो में से एक value में बदलें["P" if m >= 40 else "F" for m in marks]

Dictionary comprehension

Python – dict_comprehension.py
items = ["kaju katli", "ghewar", "rasmalai"]
price = [900, 650, 700]

menu = {name.title(): p for name, p in zip(items, price)}
print(menu)

discounted = {k: round(v * 0.9) for k, v in menu.items() if v > 680}
print(discounted)

# swap keys and values
by_price = {v: k for k, v in menu.items()}
print(by_price[650])
{'Kaju Katli': 900, 'Ghewar': 650, 'Rasmalai': 700} {'Kaju Katli': 810, 'Rasmalai': 630} Ghewar

Set comprehension

Python – set_comprehension.py
emails = ["riya@gmail.com", "AMAN@yahoo.com", "neha@gmail.com", "aman@yahoo.com"]

domains = {e.split("@")[1].lower() for e in emails}
unique_users = {e.lower() for e in emails}
print(sorted(domains))
print(len(emails), "emails,", len(unique_users), "unique")
['gmail.com', 'yahoo.com'] 4 emails, 3 unique

Nested loops और flatten करना

Python – nested.py
sections = [["Asha", "Ravi"], ["Neha"], ["Kabir", "Isha", "Om"]]

# loops are written in the same order as normal nested for-loops
all_students = [s for section in sections for s in section]
print(all_students)

table = [[r * c for c in range(1, 4)] for r in range(1, 4)]
for row in table:
    print(row)
['Asha', 'Ravi', 'Neha', 'Kabir', 'Isha', 'Om'] [1, 2, 3] [2, 4, 6] [3, 6, 9]
⚠️ पढ़ने लायक रखें

अगर comprehension में दो से ज़्यादा for या लंबी condition चाहिए, तो सामान्य loop लिखें। चालाक code से साफ़ code बेहतर है।

असली उदाहरण: बिगड़ी student list साफ़ करना

Python – clean_names.py
raw = ["  asha sharma ", "RAVI kumar", "", "neha  verma", "  ", "Kabir Singh"]

clean = [" ".join(name.split()).title() for name in raw if name.strip()]
initials = {name: "".join(part[0] for part in name.split()) for name in clean}

print(clean)
print(initials)
['Asha Sharma', 'Ravi Kumar', 'Neha Verma', 'Kabir Singh'] {'Asha Sharma': 'AS', 'Ravi Kumar': 'RK', 'Neha Verma': 'NV', 'Kabir Singh': 'KS'}

क्या comprehension तेज़ है?

Python – speed.py
import timeit

loop_code = """
result = []
for n in range(10000):
    result.append(n * 2)
"""
comp_code = "result = [n * 2 for n in range(10000)]"

t_loop = timeit.timeit(loop_code, number=300)
t_comp = timeit.timeit(comp_code, number=300)
print("comprehension faster:", t_comp < t_loop)
comprehension faster: True

आम तौर पर हाँ, लगभग 20–40%, क्योंकि append optimised C code के अंदर होता है। पर comprehension मुख्य रूप से readability के लिए चुनें; printing या saving जैसे side effects के लिए सामान्य loop लें।

आम ग़लतियाँ

ग़लतीसुधार
[x for x in data if x > 0 else 0] → SyntaxErrorif-else को for से पहले रखें: [x if x > 0 else 0 for x in data]
सिर्फ़ print के लिए comprehension: [print(x) for x in data]सामान्य for loop लिखें
बहुत लंबा nested comprehensionLoop या helper function में बाँटें
(x for x in data) को tuple समझनायह generator है; tuple(...) लें

अभ्यास

  1. Numbers की list से सिर्फ़ odd numbers के cubes की list बनाएँ।
  2. {"pen": 10, "book": 250, "bag": 799} से 18% GST जोड़कर नई dictionary बनाएँ।
  3. किसी sentence में आने वाले सभी vowels का set बनाएँ।
  4. [[1, 2], [3], [4, 5, 6]] को flatten करके सिर्फ़ even numbers रखें।

सारांश

  • [expr for x in data if cond] list बनाता है; {k: v for …} dictionary; {expr for …} set।
  • for के बाद if filter करता है; for से पहले if/else value चुनता है।
  • कई for सामान्य nested-loop क्रम में चलते हैं।
  • Readability पहले: जटिल हो या side effects हों तो loop लिखें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या Python में tuple comprehension होता है?
नहीं। (x for x in data) एक generator expression बनाता है। Tuple चाहिए तो tuple(x for x in data) लिखें।
क्या comprehension में अकेला else लगा सकते हैं?
नहीं। Filter में for के बाद सिर्फ़ if आता है। else सिर्फ़ for से पहले लिखे conditional expression का हिस्सा हो सकता है।
क्या comprehension का variable बाहर आता है?
नहीं। Python 3 में comprehension का loop variable उसके अंदर ही रहता है, जबकि सामान्य for loop का variable loop के बाद भी रहता है।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
अगला topicModules और Packages आपकी प्रगति: 16 / 66 (24%) · Lesson 17 / 66 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें