🟢 Beginner  ·  Lesson 11

Lambda, map, filter और reduce

Lambda क्या है?

Lambda एक छोटा, एक-line वाला बिना नाम (anonymous) function है। छोटे कामों के लिए सुविधाजनक जिनके लिए पूरा def नहीं लिखना चाहते।

Lambda Syntax

Python – lambda
# Normal function
def square(x):
    return x * x

# वही चीज़ lambda के रूप में
square = lambda x: x * x

print(square(5))
25

Pattern: lambda arguments: expression। expression की value अपने आप return होती है।

Program 1: Simple Lambda

Python – simple.py
add = lambda a, b: a + b
is_even = lambda n: n % 2 == 0

print(add(3, 4))
print(is_even(10))
7 True

Program 2: map() के साथ Lambda

map() किसी function को list के हर item पर लगाता है।

Python – map.py
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares)
[1, 4, 9, 16]

Lambda हर number का square करता है; map इसे पूरी list पर चलाता है।

Program 3: filter() के साथ Lambda

filter() सिर्फ वे items रखता है जहाँ function True लौटाए।

Python – filter.py
nums = [5, 12, 8, 21, 3]
big = list(filter(lambda x: x > 10, nums))
print(big)
[12, 21]

Program 4: sorted() के साथ Lambda

Lambda sorted() को बता सकता है कि किस आधार पर sort करना है।

Python – sortby.py
students = [("Aman", 88), ("Riya", 95), ("Karan", 79)]
# marks (दूसरे item) से sort
top = sorted(students, key=lambda s: s[1], reverse=True)
print(top)
[('Riya', 95), ('Aman', 88), ('Karan', 79)]

key=lambda s: s[1] sorted को marks से order करने को कहता है।

Lambda कब Use करें

  • छोटे, एक बार use होने वाले functions के लिए।
  • sorted, map, filter में key के रूप में।
  • एक expression से लंबा कुछ भी हो तो normal def use करें।

सामान्य गलतियाँ

  • lambda में कई statements डालने की कोशिश — सिर्फ एक expression allowed है।
  • map/filter के around list() भूलना (वे objects लौटाते हैं, lists नहीं)।

Practice Tasks

  1. एक lambda लिखें जो number का cube करे।
  2. map और lambda से list के हर item को double करें।
  3. filter से सिर्फ 4 अक्षर से लंबे words रखें।
  4. Lambda से names की list उनकी length के आधार पर sort करें।

सारांश

  • Lambda एक-line anonymous function है: lambda args: expression
  • map, filter, sorted के साथ common।
  • लंबे काम के लिए normal def use करें।
← 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 दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.