पाठ 14 / 47

कॉम्प्रिहेंशन और नेस्टेड डेटा

एक पंक्ति में list, dict और set बनाएँ, और कलेक्शन को जोड़ें।

List comprehension

List comprehension किसी iterable से नई सूची बनाता है, वैकल्पिक रूप से if से फ़िल्टर किया हुआ।

squares = [n * n for n in range(6)]
evens = [n for n in range(20) if n % 2 == 0]
print(squares)
print(evens)

Dict और set comprehension

यही विचार dict और set पर भी लागू होता है — बस ब्रैकेट बदलें।

squares = {n: n * n for n in range(5)}
unique_lens = {len(w) for w in ["hi", "bye", "ok"]}
print(squares)
print(unique_lens)

नेस्टेड डेटा संरचनाएँ

लिस्ट और dict नेस्ट हो सकते हैं: dicts की लिस्ट (रिकॉर्ड्स), या lists का dict (समूहीकृत डेटा) — असल प्रोग्राम में बहुत आम।

त्वरित जाँच: `[n for n in range(5) if n % 2 == 0]` क्या देता है?

  • [1, 3]
  • [0, 2, 4]
  • [0, 1, 2, 3, 4]
Answer

[0, 2, 4] — केवल सम संख्याएँ 0-4 `if` फ़िल्टर से गुज़रती हैं।