← Back

Home › Hindi › map, filter और reduce Hindi में

map(), filter() और reduce() — data पर function लागू करना

🌐 यह page Hindi में है · List comprehension Hindi में पढ़ें →

map()filter()reduce()Comprehension से तुलना

तीनों एक ही pattern हैं

ये तीनों functions किसी sequence पर दूसरा function लागू करते हैं। फर्क सिर्फ इतना है कि नतीजा किस आकार का होता है।

nums = [1, 2, 3, 4, 5]

map(fn, nums)       # हर item पर fn  ->  नतीजे की वही लंबाई
filter(fn, nums)    # fn True हो वही ->  नतीजा छोटा हो सकता है
reduce(fn, nums)    # सबको मिलाकर एक value

# तीन मूल सवाल
# map    : हर item बदलना है?         -> 5 items in, 5 items out
# filter : कुछ items चुनने हैं?      -> 5 items in, 0-5 items out
# reduce : सब मिलाकर एक जवाब चाहिए?  -> 5 items in, 1 value out

map() — हर item बदलना

nums = [1, 2, 3, 4]

list(map(lambda x: x * 2, nums))        # [2, 4, 6, 8]
list(map(str, nums))                    # ['1', '2', '3', '4']
list(map(abs, [-1, 2, -3]))             # [1, 2, 3]

names = ["asha", "ravi"]
list(map(str.upper, names))             # ['ASHA', 'RAVI']

# दो lists साथ
list(map(lambda a, b: a + b, [1, 2], [10, 20]))   # [11, 22]

# कई lists पर — छोटी वाली खत्म होते ही रुक जाता है
list(map(lambda a, b: a * b, [1, 2, 3], [10, 20]))  # [10, 40]

दो बातें ध्यान देने लायक हैं। map एक iterator लौटाता है, list नहीं — इसलिए ऊपर हर जगह list() लगा है। और method को सीधे पास कर सकते हो (str.upper), बिना lambda लपेटे।

m = map(lambda x: x * 2, [1, 2, 3])
print(m)              #   — list नहीं!
print(list(m))        # [2, 4, 6]
print(list(m))        # []   — iterator खत्म हो चुका, दोबारा खाली

filter() — items चुनना

nums = [1, -2, 3, -4, 5]

list(filter(lambda x: x > 0, nums))     # [1, 3, 5]
list(filter(None, [0, 1, "", "a", None]))   # [1, 'a']  — falsy हट गए

words = ["", "hello", "", "world"]
list(filter(None, words))               # ['hello', 'world']

# named function के साथ — पढ़ने में आसान
def passed(student):
    return student["marks"] >= 40

list(filter(passed, students))

filter(None, seq) एक काम का shorthand है: ये सारे falsy values (0, "", None, []) हटा देता है। खाली strings हटाने के लिए यही सबसे साफ तरीका है।

reduce() — सब मिलाकर एक value

reduce अलग है: ये Python 3 में built-in नहीं है, functools से import करना पड़ता है।

from functools import reduce

nums = [1, 2, 3, 4]

reduce(lambda a, b: a + b, nums)        # 10  — (((1+2)+3)+4)
reduce(lambda a, b: a * b, nums)        # 24
reduce(lambda a, b: a if a > b else b, nums)   # 4  — max
reduce(lambda a, b: a + b, nums, 100)   # 110 — 100 initial value

# step by step क्या होता है
# acc=1, x=2 -> 3
# acc=3, x=3 -> 6
# acc=6, x=4 -> 10

पर ज़्यादातर बार reduce की ज़रूरत नहीं। जो तीन काम इससे सबसे ज़्यादा कराए जाते हैं, उनके built-in मौजूद हैं — और वो पढ़ने में बेहतर हैं:

from functools import reduce

reduce(lambda a, b: a + b, nums)     # ❌  sum(nums)        लिखो
reduce(lambda a, b: a * b, nums)     # ❌  math.prod(nums)  लिखो
reduce(max, nums)                    # ❌  max(nums)        लिखो
reduce(min, nums)                    # ❌  min(nums)        लिखो

# reduce सही तब है जब logic असल में custom हो
tree = reduce(lambda acc, part: {**acc, **part}, dicts, {})

Comprehension बनाम map/filter

यही वो सवाल है जो interviews में पूछा जाता है। जवाब: ज़्यादातर मामलों में comprehension बेहतर है।

nums = [1, -2, 3, -4]

# map
list(map(lambda x: x * 2, nums))
[x * 2 for x in nums]                    # ✅ छोटा और साफ

# filter
list(filter(lambda x: x > 0, nums))
[x for x in nums if x > 0]               # ✅

# दोनों साथ
list(map(lambda x: x * 2, filter(lambda x: x > 0, nums)))
[x * 2 for x in nums if x > 0]           # ✅ बहुत साफ

तीनों को जोड़ना (pipeline)

rows = [
    {"name": "Asha",  "marks": 91},
    {"name": "Ravi",  "marks": 42},
    {"name": "Meera", "marks": 77},
]

# filter -> map -> reduce का pipeline
passed   = filter(lambda r: r["marks"] >= 50, rows)
names    = map(lambda r: r["name"], passed)
total    = reduce(lambda a, r: a + r["marks"], passed, 0)

# comprehension से वही काम, एक line में
names = [r["name"] for r in rows if r["marks"] >= 50]
total = sum(r["marks"] for r in rows if r["marks"] >= 50)
print(names, total)      # ['Asha', 'Meera'] 168

ऊपर वाला code एक गलती भी दिखाता है: passed एक iterator है, तो उसे दो जगह use करने पर दूसरी जगह खाली मिलेगा। Pipeline बनाओ तो या तो हर step को list() में लो, या comprehension लिखो।

आम गलतियाँ

result = map(str.upper, ["a", "b"])
print(result)          #   — values नहीं दिखीं
print(list(result))    # ['A', 'B']
print(list(result))    # []   — iterator खत्म, चुपचाप खाली

from functools import reduce
reduce(lambda a, b: a + b, [])       # TypeError: reduce() of empty
reduce(lambda a, b: a + b, [], 0)    # 0  — initial value देने से ठीक

🛠️ Practice करो (free, browser में)

पढ़ना काफी नहीं — यही bug खुद fix करके देखो। नीचे के problems browser में ही चलते हैं, कोई install नहीं, कोई login नहीं।

सारे free problems देखो →

अक्सर पूछे जाने वाले सवाल

map, filter और reduce में क्या फर्क है?

map हर item पर function लगाता है और वही लंबाई लौटाता है। filter सिर्फ वो items रखता है जिन पर function True हो। reduce सब items को मिलाकर एक value बनाता है।

क्या map एक list लौटाता है?

नहीं, iterator लौटाता है। इसलिए print(map(...)) पर object का address दिखता है। Values चाहिए तो list() में लपेटो। Iterator एक बार ही चलता है — दोबारा खाली मिलेगा।

reduce के लिए import क्यों चाहिए?

Python 3 में reduce built-in नहीं रहा, functools module में चला गया। इसलिए from functools import reduce लिखना पड़ता है। Python 2 में ये built-in था।

Comprehension बेहतर है या map/filter?

जब lambda लिखना पड़े तब comprehension ज़्यादातर छोटा और साफ होता है। map/filter तब अच्छे हैं जब function पहले से मौजूद हो — जैसे map(str, nums) या filter(None, words)।

filter(None, seq) क्या करता है?

सारे falsy values हटा देता है — 0, खाली string, None, खाली list। खाली strings या None वाली entries हटाने का सबसे साफ तरीका यही है।

आगे पढ़ो