1.2.32 · D1 · HinglishIntroduction to Programming (Python)

FoundationsLambda functions — anonymous, used with map - filter

2,523 words11 min read↑ Read in English

1.2.32 · D1 · Coding › Introduction to Programming (Python) › Lambda functions — anonymous, used with map - filter

Ek bhi lambda chhune se pehle, tumhe kuch symbols aur ideas mein fluent hona chahiye jo parent note maan leta hai ki tumhare paas pehle se hain. Yeh page unhe ek-ek karke zero se banata hai, us order mein jis order mein woh ek doosre pe depend karte hain. Yahan koi symbol use nahi hoga jab tak usse draw nahi kar diya jaata.


0 · "Function" asal mein hota kya hai (machine waali picture)

Figure 1 (neeche) — machine ki picture: ek input arrow box mein jaata hai, rule chalta hai, ek output arrow nikalta hai.

Figure — Lambda functions — anonymous, used with map - filter

Figure 1 dekho. Box woh machine hai. Orange arrow jo andar ja raha hai woh argument 5 le jaata hai; plum arrow jo bahar aa raha hai woh return value 25 le ke aata hai. Python mein tum aisi machine def se banate ho:

def square(x):     # x is the input arrow
    return x * x   # this is the output arrow
  • WHAT def square(x): karta hai — yeh ek nayi machine square ko naam deta hai jo ek input expect karti hai, jise woh x kehta hai.
  • WHY hume return chahiye — iske bina machine kuch produce nahi karti (None); return woh output chute hai.
  • Yeh Functions and def idea hai. Lambda, jo baad mein aayega, wahi machine bina naam ke born hoti hai.

1 · Rule ke andar ke symbols

Parent note x * 2, x % 2 == 0, x * x jaisi rules likhta hai. Chaliye har symbol ko earn karte hain.

Figure 2 (neeche) — kyun x % 2 ek even/odd detector hai: items ko pairs mein baanto aur bacha hua padho.

Figure — Lambda functions — anonymous, used with map - filter

Figure 2 dekho. x items ki ek pile ko pairs mein split karo. Agar kuch nahi bachta, remainder hai 0even. Agar ek item dangles, remainder hai 1odd. Toh x % 2 == 0 poochh raha hai "kya pairs cleanly nikle?" — parent ke even-number example mein exactly yahi test use hota hai.


2 · True, False, aur "truthy" — haan/na ki duniya

filter (jise hum §5 mein define karte hain) woh items rakhta hai jahan rule truthy hoti hai. Toh hume yeh word achhi tarah samajhna chahiye.

Figure 3 (neeche) — har value do bins mein se ek mein jaati hai: falsy (empty/nothing) ya truthy (baaki sab).

Figure — Lambda functions — anonymous, used with map - filter

Figure 3 dekho. Rule koi memorised blacklist nahi hai — yeh ek general principle hai:

  • WHY yeh important hai: §5 mein tum dekhoge ki filter(f, it) tab x rakhta hai jab bool(f(x)) True hota hai. Toh parent ka idiom filter(lambda x: x, items) har woh item rakhta hai jo zero-ya-empty nahi hai.

3 · Collections jo tum walk kar sako: the iterable

Parent [1, 2, 3, 4] jaisi lists map/filter mein feed karta hai. Yeh hai kya, aur shape kyun matter karta hai?

for x in [1, 2, 3]:   # colon ends the header; the indented body runs once per x
    print(x)          # x becomes 1, then 2, then 3
  • Square brackets [...] ek list banate hain; round brackets (...) ek tuple banate hain (ek fixed chhota group, jaise example 4 mein pair (3, 'a')).
  • WHY map/filter ko ek iterable chahiye — woh secretly for loops hain (parent yeh prove karta hai unhe rebuild karke), aur ek for loop ko kuch walk karne ke liye chahiye.

4 · Indexing: p[1] se andar pahunchna

Example 4 key=lambda p: p[1] use karta hai. Woh [1] indexing hai, list nahi.


5 · Do tools: map aur filter asal mein kya karte hain

Parent rules ko map aur filter ko deta hai lekin unhe kabhi kholke nahi dikhata. Yahan unka exact behaviour hai.

§3 se for loops se tumhare paas unki true definition padhne ke liye har symbol hai — woh sirf yeh hain:

def my_map(f, it):
    out = []
    for x in it:          # walk the iterable
        out.append(f(x))  # transform: store f(x)
    return out
 
def my_filter(f, it):
    out = []
    for x in it:
        if f(x):          # select: keep x only when f(x) is truthy
            out.append(x)
    return out
  • WHAT har ek karta hai — map har x ke liye f(x) store karta hai; filter x sirf tab store karta hai jab f(x) truthy ho.
  • WHY §2 ki truthiness matter karti thi — yeh exactly woh if f(x): test hai my_filter mein.

6 · Ek function ko value ki tarah pass karna — aur aakhirkar, lambda

Yahan keystone hai: map(f, it) ek function f ko uske pehle argument ke roop mein leta hai.

def apply(f, x):   # f is a MACHINE handed in as a value
    return f(x)
 
apply(square, 5)   # -> 25   (square the machine, not square(5))
  • WHAT abhi hua — square (machine khud) andar pass ki gayi aur phir andar call ki gayi.
  • WHY yeh lambdas ko unlock karta hai — agar ek machine sirf ek value hai jo tum pass karte ho, toh ek ek-baar-use machine ko def karke naam dena wasteful hai.

Ab hum directly parent page ke star se mil sakte hain:

Figure 1 ki machine picture ko lambda mein translate karo, side by side:

def square(x):        # named machine
    return x * x
 
square = lambda x: x * x   # SAME machine, written in one line
 
add_one = lambda x: x + 1  # concrete tiny example
add_one(9)                 # -> 10
  • WHAT lambda x: x + 1 ka matlab hai — "input x, output x + 1", exactly Figure 1 ki machine alag rule ke saath.
  • WHY koi return nahi — single expression x + 1 hi output hai; ek lambda ke paas statements ke liye jagah nahi hoti.
  • Yeh kaise plug in hota hai — is chhoti machine ko seedha §5 ke tools ko do: list(map(lambda x: x + 1, [0, 9])) deta hai [1, 10]. Woh inline lambda x: x + 1 hi parent note ka poora pitch hai.

Prerequisite map — ise kaise padhen

Neeche wala diagram ek dependency chart hai: ek arrow A --> B ka matlab hai "B samajhne se pehle tumhe A chahiye." Top boxes (jo kisi pe depend nahi karte) se shuru karo, arrows ko neeche follow karo, aur tum bottom box mein parent topic pe pahuncho. Agar tum har arrow trace kar sako aur uska label explain kar sako, tum ready ho.

named with def

body uses

groups blocks

comparisons give

for loop walks

filter keeps truthy

pass rule inline

receive the rule

reach into tuples

transform rule

Function is a machine

Symbols star percent equalequal

Colon indent commas

True False truthy

Iterable you can walk

Indexing p at 1

Functions are values

map and filter

Lambda with map and filter

Top-down padho: punctuation aur machine idea pehle aate hain; machine do mein split hoti hai "isko naam do" (functions-as-values) aur "iske andar kaunse symbols rehte hain". Booleans aur iterables do tools map/filter ko feed karte hain, aur woh tools plus first-class functions aakhirkar lambda mein milte hain.


Equipment checklist

Ek function kya hai, ek picture mein?
Ek machine: input andar jaata hai, rule chalta hai, ek output wapas aata hai.
return kya karta hai?
Ek value ko function se output ke roop mein bahar bhejta hai; iske bina tumhe None milta hai.
def f(x): mein colon : kya karta hai?
Header line ko khatam karta hai aur indented block introduce karta hai jo iske belong karta hai.
Python kaise jaanta hai ki kaunsi lines ek block banati hain?
Indentation se — same amount se push ki gayi lines ek block hain.
7 % 2 kya evaluate karta hai, aur kyun?
1 — yeh 7 ko 2 se divide karne ke baad remainder hai.
Tum test kaise karte ho ki x even hai?
x % 2 == 0 (pairs ke baad remainder zero hai).
= aur == mein difference?
= ek value ko naam mein store karta hai; == poochhta hai "kya yeh equal hain?" aur True/False return karta hai.
General falsy rule batao.
Ek value falsy hoti hai jab woh numeric zero ho, koi bhi empty container ('', [], (), {}, set(), range(0)) ho, ya None/False ho; baaki sab truthy hai.
Iterable kya hai?
Koi bhi cheez jis par tum for loop se ek ek item karke walk kar sako (list, tuple, string).
p = (3, 'a') ke liye, p[1] kya hai?
'a' — indexing 0 se shuru hoti hai, toh position 1 doosra item hai.
map(f, it) kya return karta hai aur kya karta hai?
Ek lazy iterator jo it mein har x ke liye f(x) yield karta hai (har element ko transform karta hai).
filter(f, it) kya karta hai?
Har x tab yield karta hai jab bool(f(x)) True ho (truthy waale select karta hai).
Machine x -> x+1 ko lambda mein likho.
lambda x: x + 1 — single expression auto-return hota hai.

Connections

  • Functions and def — woh named machine jiska lambda anonymous version hai.
  • First-class functions — ek function ko argument ke roop mein pass kyun kiya ja sakta hai.
  • Higher-order functions — tools jaise map/filter jo ek function lete hain.
  • Iterators and lazy evaluationmap/filter kya return karte hain ek iterable feed karne ke baad.
  • sorted and key functions — jahan indexing p[1] ek sort key ban jaata hai.
  • List comprehensions — ek alternative jo yahi symbols use karta hai.