The Story That Explains Functional Tools 🏭Functional Tools समझाने वाली कहानी 🏭一个讲清函数式工具的故事 🏭
Station 1 — the Painter. Every apple gets a wax coat. One apple in, one apple out. Same count, transformed. That is
map().Station 2 — the Inspector. Bruised apples are thrown out; good ones pass. Fewer apples come out than went in. That is
filter().Station 3 — the Weigher. The remaining apples drop onto one scale. Many apples go in, one total weight comes out. That is
reduce().And the small handwritten notes on each station — "wax it", "keep if not bruised", "add to the running total" — are lambdas: tiny unnamed functions that tell each station what to do.
Station 1 — रंगने वाला। हर सेब पर wax चढ़ती है। एक सेब अंदर, एक सेब बाहर। गिनती वही, रूप बदला। यह है
map()।Station 2 — जाँचने वाला। दबे हुए सेब फेंक दिए जाते हैं; अच्छे आगे जाते हैं। जितने गए उससे कम निकलते हैं। यह है
filter()।Station 3 — तौलने वाला। बचे हुए सेब एक तराज़ू पर गिरते हैं। कई सेब अंदर, एक कुल वज़न बाहर। यह है
reduce()।और हर station पर लगी छोटी हाथ से लिखी पर्चियाँ — "wax लगाओ", "दबा न हो तो रखो", "कुल में जोड़ो" — ये हैं lambdas: छोटे बेनाम functions जो हर station को बताते हैं कि क्या करना है।
工位 1 — 上蜡工。每个苹果都上一层蜡。进一个,出一个。数量不变,形态改变。这就是
map()。工位 2 — 质检员。有伤的苹果被扔掉,好的通过。出来的比进去的少。这就是
filter()。工位 3 — 称重员。剩下的苹果都落在一台秤上。很多苹果进去,出来的是 一个总重量。这就是
reduce()。而每个工位上手写的小纸条 —"上蜡"、"没伤才留下"、"加到总数里"— 就是 lambda:告诉每个工位该做什么的小小匿名函数。
Python's functional tools — lambda, map, filter, reduce, zip, enumerate, sorted and friends — are the vocabulary for "do this to every item", "keep only these" and "combine into one" without writing the loop yourself.
Python के functional tools — lambda, map, filter, reduce, zip, enumerate, sorted और साथी — "हर item के साथ यह करो", "सिर्फ़ ये रखो" और "सबको एक में मिलाओ" कहने की भाषा हैं, बिना ख़ुद loop लिखे।
Python 的函数式工具 — lambda、map、filter、reduce、zip、enumerate、sorted 等 — 是表达"对每个元素做这件事"、"只保留这些"和"合并成一个"的词汇,无需自己写循环。
Almost every tool here follows one pattern: a small function + an iterable. The built-in does the looping; the small function (often a lambda) says what to do with each item. You describe the transformation, not the plumbing.
यहाँ लगभग हर tool एक ही pattern पर चलता है: एक छोटा function + एक iterable। Built-in loop करता है; छोटा function (अक्सर lambda) बताता है कि हर item के साथ क्या करना है। आप बदलाव का वर्णन करते हैं, नलसाज़ी का नहीं।
这里几乎每个工具都遵循同一个模式:一个小函数 + 一个可迭代对象。内置函数负责循环;小函数(通常是 lambda)说明每个元素该怎么处理。你描述的是 转换,而不是管道细节。
Look for the interactive boxes: the Pipeline Factory (Section 06), the Zip & Enumerate Lab (08), the Sort Key Lab (09) and the any/all Detective (10). Their data comes from real Python — the pipeline even shows the exact order in which Python called each lambda.
Interactive डिब्बे खोजें: Pipeline Factory (Section 06), Zip & Enumerate Lab (08), Sort Key Lab (09) और any/all Detective (10)। इनका data असली Python से आता है — pipeline तो वह सटीक क्रम भी दिखाती है जिसमें Python ने हर lambda बुलाया।
请留意这些互动框:Pipeline Factory(第 06 节)、Zip & Enumerate Lab(08)、Sort Key Lab(09)和 any/all Detective(10)。它们的数据来自真实 Python — 流水线甚至显示了 Python 调用每个 lambda 的确切顺序。
Lambda — The Anonymous Function λLambda — बेनाम Function λLambda — 匿名函数 λ
Before map and filter can shine, you need lambda — Python's way of writing a one-expression function without giving it a name. Think of it as a disposable function you write right where you need it.
map और filter के चमकने से पहले आपको lambda चाहिए — Python का तरीका एक-expression वाला function बिना नाम दिए लिखने का। इसे ऐसा function समझें जिसे आप वहीं लिखते हैं जहाँ ज़रूरत है, और फेंक देते हैं।
在 map 和 filter 大显身手之前,你需要 lambda — Python 不起名字就写出单表达式函数的方式。把它看作在需要的地方当场写、用完就扔的函数。
# The traditional way - a named function
def square(x):
return x * x
# The lambda way - anonymous, one line
square_lambda = lambda x: x * x # (named here only to compare - see Rule 1)
print(square(5))
print(square_lambda(5))
print(square.__name__, "vs", square_lambda.__name__)
lambda — starts the function.
lambda — function शुरू करता है।
lambda — 开始一个函数。
: is the return value — no return keyword.
: के बाद जो भी है, वही return value है — return keyword नहीं।
: 之后的内容 就是 返回值 — 不写 return。
for loops, no if blocks (but a conditional expression is fine).
एक अकेला expression — कोई statements नहीं, for loops नहीं, if blocks नहीं (पर conditional expression चलता है)।
单个表达式 — 不能有语句、for 循环或 if 块(但条件表达式可以)。
Lambda with Several Argumentsकई Arguments वाला Lambda多参数的 lambda
add = lambda x, y: x + y
distance = lambda x1, y1, x2, y2: ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
greet = lambda name, greeting="Namaste": f"{greeting}, {name}!"
print(add(3, 4))
print(distance(0, 0, 3, 4))
print(greet("Aarav"))
print(greet("Meera", "Hey"))
Lambda with a Conditional ExpressionConditional Expression वाला Lambda带条件表达式的 lambda
# You CAN'T write if/else statements - but a conditional expression is fine
grade = lambda score: "pass" if score >= 40 else "fail"
print(grade(75))
print(grade(32))
A lambda holds a single expression, nothing more. No statements, no return, no loops, no try/except. If you need those, write a real def. And if you want to give a lambda a name (square = lambda x: x*x), write a def instead — the style guide PEP 8 says so, and a def shows its real name in tracebacks (see <lambda> above). The examples here name lambdas only so you can see them work.
Lambda में सिर्फ़ एक expression होता है, बस। कोई statements नहीं, return नहीं, loops नहीं, try/except नहीं। अगर ये चाहिए, तो असली def लिखें। और अगर lambda को नाम देना चाहते हैं (square = lambda x: x*x), तो उसकी जगह def लिखें — style guide PEP 8 यही कहती है, और def tracebacks में अपना असली नाम दिखाता है (ऊपर <lambda> देखें)। यहाँ के उदाहरण lambdas को नाम सिर्फ़ इसलिए देते हैं ताकि आप उन्हें चलते देख सकें।
lambda 只能容纳 一个表达式,仅此而已。没有语句、没有 return、没有循环、没有 try/except。需要这些就写真正的 def。如果想给 lambda 起名字(square = lambda x: x*x),就改写成 def — 风格指南 PEP 8 就是这么说的,而且 def 在 traceback 中显示真实名字(见上面的 <lambda>)。这里的示例给 lambda 起名,只是为了让你看到它们运行。
A Classic Trap — Lambdas in a Loopएक मशहूर जाल — Loop में Lambdas经典陷阱 — 循环里的 lambda
# The late-binding trap: every lambda sees the LAST value of i
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
# Fix: freeze the current value with a default argument
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])
A lambda does not copy the value of i when it is created. It looks i up when it is called — and by then the loop has finished and i is 2. A default argument (i=i) is evaluated at creation time, so it freezes the value.
Lambda बनते समय i की value copy नहीं करता। वह i को तब देखता है जब उसे बुलाया जाता है — और तब तक loop ख़त्म हो चुका होता है और i 2 है। Default argument (i=i) बनते समय ही evaluate होता है, इसलिए value जम जाती है।
lambda 被创建时不会复制 i 的值。它在 被调用 时才查找 i — 那时循环已结束,i 是 2。默认参数(i=i)在创建时求值,所以能把值固定下来。
Map vs Filter vs Reduce — Three Shapes 🔷Map बनाम Filter बनाम Reduce — तीन आकार 🔷Map、Filter、Reduce — 三种形状 🔷
These three look alike in code but do very different things to your data. Picture the shape of each and you will never mix them up.
Code में ये तीनों एक जैसे दिखते हैं पर आपके data के साथ बिल्कुल अलग काम करते हैं। हर एक का आकार कल्पना करें और आप इन्हें कभी नहीं मिलाएँगे।
这三者在代码里看起来很像,对数据做的事却截然不同。在脑中描绘出各自的 形状,就再也不会混淆。
Same input [1, 2, 3, 4], three different shapes of output: map keeps the count, filter shrinks it, reduce collapses it to one value.
एक ही input [1, 2, 3, 4], output के तीन अलग आकार: map गिनती रखता है, filter उसे घटाता है, reduce उसे एक value में समेट देता है।
同样的输入 [1, 2, 3, 4],三种不同形状的输出:map 保持数量,filter 减少数量,reduce 合并成一个值。
map() — Transform Every Item 🎨map() — हर Item बदलें 🎨map() — 转换每个元素 🎨
map(function, iterable) calls function on every item and gives back a lazy iterator. Wrap it in list() to get the results.
map(function, iterable) हर item पर function बुलाता है और एक lazy iterator लौटाता है। नतीजे पाने के लिए इसे list() में लपेटें।
map(function, iterable) 对每个元素调用 function,返回一个 惰性迭代器。用 list() 包起来才能得到结果。
nums = [1, 2, 3, 4, 5]
# Traditional way: for loop with append
squared = []
for n in nums:
squared.append(n ** 2)
print(squared)
# map + lambda way - one line
squared = list(map(lambda n: n ** 2, nums))
print(squared)
Map with a Named Functionनाम वाले Function के साथ Map配合具名函数的 map
# Any function works - not just lambdas
words = ["apple", "BANANA", "Cherry"]
print(list(map(str.lower, words)))
print(list(map(len, words)))
# Read numbers typed on one line
line = "12 7 30 5"
print(list(map(int, line.split())))
map(int, line.split()) is the classic way to read several numbers typed on one line — you will see it in many competitive-programming solutions.
map(int, line.split()) एक line पर लिखी कई संख्याएँ पढ़ने का मशहूर तरीका है — competitive programming के कई solutions में यह दिखता है।
map(int, line.split()) 是读取一行中多个数字的经典写法 — 在很多算法竞赛的解答里都能看到。
Map with Several Iterables — and Lazinessकई Iterables के साथ Map — और आलस多个可迭代对象的 map — 以及惰性
# The function takes as many arguments as you pass iterables
prices = [10, 20, 30]
quantities = [2, 3, 1]
print(list(map(lambda p, q: p * q, prices, quantities)))
# map is lazy: it computes nothing until you ask
squares = map(lambda n: n * n, [1, 2, 3])
print(squares) # a map object, not values
print(list(squares)) # now the values are computed
print(list(squares)) # used up! a map works only once
In Python 3, map() gives a map object — nothing is computed until you loop over it. That saves memory, but it can be used only once: the second list() above is empty. (The 0x7f… address in the output changes every run.)
Python 3 में map() एक map object देता है — जब तक आप उस पर loop न करें, कुछ compute नहीं होता। इससे memory बचती है, पर इसे सिर्फ़ एक बार इस्तेमाल कर सकते हैं: ऊपर का दूसरा list() ख़ाली है। (Output में 0x7f… address हर run में बदलता है।)
在 Python 3 中,map() 返回一个 map 对象 — 在你遍历它之前什么都不计算。这样省内存,但它 只能用一次:上面第二个 list() 是空的。(输出中的 0x7f… 地址每次运行都会变。)
map(..., strict=True)Python 3.14: map(..., strict=True)Python 3.14:map(..., strict=True)With several iterables, map stops at the shortest one, just like zip. Since Python 3.14 you can pass strict=True to get a ValueError when the lengths differ, instead of silently losing items.
कई iterables के साथ map, zip की तरह सबसे छोटे पर रुक जाता है। Python 3.14 से आप strict=True दे सकते हैं, ताकि लंबाई अलग होने पर items चुपचाप खोने की जगह ValueError मिले।
传入多个可迭代对象时,map 和 zip 一样在最短的那个处停止。从 Python 3.14 起,可以传 strict=True,长度不同时抛出 ValueError,而不是悄悄丢掉元素。
filter() — Keep Only What Passes 🔍filter() — सिर्फ़ पास होने वाले रखें 🔍filter() — 只保留通过的元素 🔍
filter(function, iterable) keeps only the items for which function returns a truthy value. It is lazy, just like map.
filter(function, iterable) सिर्फ़ वे items रखता है जिनके लिए function truthy value लौटाए। यह भी map की तरह lazy है।
filter(function, iterable) 只保留 function 返回真值的元素。它和 map 一样是惰性的。
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep only even numbers
print(list(filter(lambda n: n % 2 == 0, nums)))
# None as the function = "keep truthy items"
raw = ["Aarav", "", "Meera", None, "Kabir", "", 0, []]
print(list(filter(None, raw)))
filter(None, ...) Idiomfilter(None, ...) का मुहावराfilter(None, ...) 惯用法Passing None as the function means "keep truthy items only". Empty strings, 0, None and empty containers are all dropped — a one-line cleanup for messy data. Careful: it also drops a real 0 that you might want to keep.
None को function के रूप में देने का मतलब है "सिर्फ़ truthy items रखो"। ख़ाली strings, 0, None और ख़ाली containers सब हट जाते हैं — गंदे data की एक-line सफ़ाई। सावधान: यह असली 0 को भी हटा देता है जिसे शायद आप रखना चाहें।
把 None 作为函数传入,意思是"只保留真值元素"。空字符串、0、None 和空容器都会被丢掉 — 一行清理脏数据。注意:它也会丢掉你可能想保留的真实的 0。
reduce() — Collapse to a Single Value ⚖️reduce() — एक Value में समेटें ⚖️reduce() — 归约为单个值 ⚖️
reduce() lives in the functools module (Python 3 moved it out of the built-ins). It takes a function of two arguments — the running result and the next item — and applies it from left to right until one value is left.
reduce() functools module में रहता है (Python 3 ने इसे built-ins से बाहर निकाला)। यह दो arguments वाला function लेता है — चलता नतीजा और अगला item — और उसे बाएँ से दाएँ लगाता है जब तक एक value न बचे।
reduce() 位于 functools 模块(Python 3 把它移出了内置函数)。它接收一个 两个参数 的函数 — 当前累计结果和下一个元素 — 从左到右依次应用,直到只剩一个值。
from functools import reduce
# Sum: (((1+2)+3)+4)+5 = 15
total = reduce(lambda acc, x: acc + x, [1, 2, 3, 4, 5])
# Product: 1*2*3*4*5 = 120
product = reduce(lambda acc, x: acc * x, [1, 2, 3, 4, 5])
# Max by hand: keep the bigger of each pair
biggest = reduce(lambda a, b: a if a > b else b, [3, 7, 1, 9, 4])
print(total, product, biggest)
Reduce with a Start ValueStart Value के साथ Reduce带初始值的 reduce
from functools import reduce
# The 3rd argument is the STARTING value of the accumulator
print(reduce(lambda acc, x: acc + x, [], 0)) # empty list: returns 0
print(reduce(lambda acc, x: acc + x, [1, 2, 3], 100)) # 100 + 1 + 2 + 3
# Without a start value, an empty list is an error
try:
reduce(lambda acc, x: acc + x, [])
except TypeError as e:
print("TypeError:", e)
sum(), max(), min() over reduce()reduce() की जगह sum(), max(), min() को तरजीह दें优先用 sum()、max()、min() 而不是 reduce()Python has ready-made tools for the common reductions: sum, max, min, any, all, and math.prod for products. They are faster, clearer and need no lambda. Keep reduce for custom logic like the running bank balance in Section 12.
आम reductions के लिए Python के पास तैयार tools हैं: sum, max, min, any, all, और गुणा के लिए math.prod। ये तेज़, साफ़ हैं और lambda नहीं माँगते। reduce को Section 12 के चलते bank balance जैसे custom logic के लिए रखें।
Python 为常见的归约提供了现成工具:sum、max、min、any、all,求积用 math.prod。它们更快、更清晰,也不需要 lambda。把 reduce 留给自定义逻辑,比如第 12 节的银行余额。
Try It — Pipeline Factoryकरके देखें — Pipeline Factory动手试试 — 流水线工厂
Build a pipeline from filter, map and reduce, then press Play. Every step is a real call recorded from Python, in the real order. Watch how one item travels the whole line before the next one starts — that is laziness. Try the order buttons: filter → map and map → filter can give different answers. And try x > 100 with nums and the max reducer to see an empty pipeline crash.
filter, map और reduce से pipeline बनाएँ, फिर चलाएँ दबाएँ। हर कदम Python से दर्ज की गई असली call है, असली क्रम में। देखें कि अगला item शुरू होने से पहले एक item पूरी line कैसे पार करता है — यही laziness है। क्रम वाले buttons आज़माएँ: filter → map और map → filter अलग जवाब दे सकते हैं। और ख़ाली pipeline का crash देखने के लिए nums के साथ x > 100 और max reducer आज़माएँ।
用 filter、map 和 reduce 搭一条流水线,然后点 播放。每一步都是从 Python 记录下的真实调用,顺序也是真实的。看一个元素如何先走完整条线,下一个才开始 — 这就是惰性。试试顺序按钮:filter → map 和 map → filter 可能给出不同答案。再试试 nums 配 x > 100 和 max 归约器,看看空流水线如何崩溃。
zip() — Pair Up Iterables 🤝zip() — Iterables की जोड़ी बनाएँ 🤝zip() — 把可迭代对象配对 🤝
zip() takes any number of iterables and gives back tuples of items that sit at the same position. Think of a zipper: the left and right teeth lock together one pair at a time.
zip() कितने भी iterables लेता है और एक ही position पर बैठे items के tuples लौटाता है। Zipper सोचें: बाएँ और दाएँ दाँत एक-एक जोड़ी करके जुड़ते हैं।
zip() 接收任意多个可迭代对象,返回由相同位置的元素组成的元组。想象一条拉链:左右两排齿一对一对地扣在一起。
names = ["Aarav", "Meera", "Kabir"]
scores = [85, 92, 78]
ages = [20, 22, 21]
for name, score in zip(names, scores):
print(f"{name}: {score}")
for name, score, age in zip(names, scores, ages):
print(f"{name} ({age}): scored {score}")
print(dict(zip(names, scores)))
# Unzip with zip(*...) - like a transpose
pairs = [("Aarav", 85), ("Meera", 92), ("Kabir", 78)]
who, marks = zip(*pairs)
print(who)
print(marks)
When the Lists Have Different Lengthsजब Lists की लंबाई अलग हो当列表长度不同时
from itertools import zip_longest
names = ["Aarav", "Meera", "Kabir", "Isha"]
scores = [85, 92, 78] # one score is missing!
print(list(zip(names, scores))) # Isha silently disappears
print(list(zip_longest(names, scores, fillvalue="-")))
try:
list(zip(names, scores, strict=True)) # Python 3.10+
except ValueError as e:
print("ValueError:", e)
zip Drops Data Silentlyzip चुपचाप Data हटा देता हैzip 会悄悄丢数据By default zip stops at the shortest input — Isha vanished with no error. If the lists should match, write zip(..., strict=True) (Python 3.10+) so a mismatch is caught at once. If you want to keep everything, use itertools.zip_longest.
Default रूप से zip सबसे छोटे input पर रुकता है — Isha बिना error के ग़ायब हो गई। अगर lists का मेल होना चाहिए, तो zip(..., strict=True) (Python 3.10+) लिखें ताकि गड़बड़ी तुरंत पकड़ी जाए। सब कुछ रखना हो तो itertools.zip_longest इस्तेमाल करें।
默认情况下 zip 在最短的输入处停止 — Isha 消失了,却没有任何报错。如果列表 应该 等长,就写 zip(..., strict=True)(Python 3.10+),不匹配会立刻被发现。想全部保留就用 itertools.zip_longest。
enumerate() — Index and Value Together 🔢enumerate() — Index और Value साथ-साथ 🔢enumerate() — 索引与值一起 🔢
enumerate() replaces the clumsy for i in range(len(...)). It pairs each item with a counter that starts at 0 — or wherever you say.
enumerate() भद्दे for i in range(len(...)) की जगह लेता है। यह हर item को एक counter के साथ जोड़ता है जो 0 से शुरू होता है — या जहाँ से आप कहें।
enumerate() 取代笨拙的 for i in range(len(...))。它给每个元素配一个计数器,从 0 开始 — 或从你指定的数开始。
fruits = ["apple", "banana", "cherry"]
# The old way - works, but noisy
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
# The Pythonic way
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Start counting from 1 (for people, not programs)
for rank, medal in enumerate(["Gold", "Silver", "Bronze"], start=1):
print(f"#{rank} - {medal}")
Try It — Zip & Enumerate Labकरके देखें — Zip & Enumerate Lab动手试试 — Zip 与 Enumerate 实验室
Four names, but only three scores. Pick a tool and see who gets paired, who gets dropped (struck through) and who gets a filler. Every result is real Python output.
चार नाम, पर सिर्फ़ तीन scores। एक tool चुनें और देखें किसकी जोड़ी बनी, कौन हटा (कटा हुआ) और किसे filler मिला। हर नतीजा असली Python output है।
四个名字,却只有三个分数。选一个工具,看看谁被配对、谁被丢掉(划线)、谁得到了填充值。每个结果都是真实的 Python 输出。
sorted() with a Key Function 🏆Key Function के साथ sorted() 🏆带 key 函数的 sorted() 🏆
sorted() can sort by any value you can compute from an item, using the key argument. Python calls the key function once per item, then sorts by those keys. This is where lambdas really shine.
sorted(), key argument से किसी भी ऐसी value से sort कर सकता है जो item से निकाली जा सके। Python हर item के लिए key function एक बार बुलाता है, फिर उन keys से sort करता है। यहीं lambdas असल में चमकते हैं।
sorted() 借助 key 参数,可以按能从元素算出的 任何 值排序。Python 对每个元素调用一次 key 函数,再按这些键排序。这正是 lambda 大放异彩的地方。
students = [
{"name": "Aarav", "score": 85, "age": 22},
{"name": "Meera", "score": 92, "age": 20},
{"name": "Kabir", "score": 78, "age": 25},
{"name": "Diya", "score": 92, "age": 23},
]
# Sort by score, high to low
by_score = sorted(students, key=lambda s: s["score"], reverse=True)
# Score high to low, then age low to high (tie-breaker)
compound = sorted(students, key=lambda s: (-s["score"], s["age"]))
# Sort strings by their length, or ignoring case
words = ["banana", "pi", "Apple", "kiwi", "Cherry"]
print("By score: ", [s["name"] for s in by_score])
print("Compound: ", [s["name"] for s in compound])
print("By length:", sorted(words, key=len))
print("Plain: ", sorted(words))
print("No case: ", sorted(words, key=str.lower))
Notice "Plain" vs "No case": a plain string sort puts every capital letter before every small letter, so "Cherry" jumps ahead of "banana". key=str.lower fixes it.
"Plain" और "No case" पर ध्यान दें: सामान्य string sort हर बड़े अक्षर को हर छोटे अक्षर से पहले रखता है, इसलिए "Cherry", "banana" से आगे कूद जाता है। key=str.lower इसे ठीक करता है।
注意 "Plain" 和 "No case" 的区别:普通字符串排序把所有大写字母排在所有小写字母前面,所以 "Cherry" 跳到了 "banana" 前面。key=str.lower 能修正它。
Try It — Sort Key Labकरके देखें — Sort Key Lab动手试试 — 排序键实验室
Pick a key and watch the rows slide into their new places. The orange column shows the key Python actually compares. Look for ties — and see that rows with equal keys keep their original order.
एक key चुनें और rows को अपनी नई जगहों पर खिसकते देखें। नारंगी column वह key दिखाता है जिसकी Python असल में तुलना करता है। बराबरी देखें — और ध्यान दें कि बराबर keys वाली rows अपना मूल क्रम रखती हैं।
选一个键,看各行滑到新位置。橙色列显示 Python 实际比较的键。留意并列的情况 — 键相等的行会保持原来的顺序。
Return a tuple from the key function and you get multi-level sorting — Python compares tuples item by item. Put a minus sign in front of a number to sort that part high-to-low (-s["score"]). For text you cannot use a minus; sort twice instead, or use reverse=True on the whole thing. operator.itemgetter("score") is a fast alternative to lambda s: s["score"].
Key function से tuple लौटाएँ और आपको कई-स्तर की sorting मिलती है — Python tuples की तुलना item-by-item करता है। किसी संख्या के आगे minus लगाएँ ताकि वह हिस्सा बड़े-से-छोटे sort हो (-s["score"])। Text पर minus नहीं लगा सकते; दो बार sort करें, या पूरे पर reverse=True लगाएँ। operator.itemgetter("score"), lambda s: s["score"] का तेज़ विकल्प है।
让 key 函数返回 元组,就能实现多级排序 — Python 会逐项比较元组。在数字前加负号,这一部分就从大到小排(-s["score"])。文本不能加负号;可以排序两次,或对整体用 reverse=True。operator.itemgetter("score") 是 lambda s: s["score"] 的快速替代。
any() and all() — Quick Truth Tests ✅any() और all() — झटपट सच की जाँच ✅any() 和 all() — 快速真值测试 ✅
any() returns True if at least one item is truthy. all() returns True only if every item is. Both stop the moment the answer is decided.
any() True लौटाता है अगर कम से कम एक item truthy हो। all() True तभी लौटाता है जब हर item truthy हो। दोनों जवाब तय होते ही रुक जाते हैं।
只要 至少一个 元素为真,any() 就返回 True。只有 每个 元素都为真,all() 才返回 True。两者在答案确定的那一刻就停止。
nums = [2, 4, 6, 8, 10]
print(any(n > 5 for n in nums)) # at least one?
print(any(n > 100 for n in nums))
print(all(n % 2 == 0 for n in nums)) # every one?
print(all(n > 5 for n in nums))
# Edge cases worth remembering
print(any([]), all([])) # empty: any -> False, all -> True
form = {"name": "Aarav", "email": "a@x.com", "age": 30}
required = ["name", "email", "age"]
if all(form.get(k) for k in required):
print("Form is complete")
any([]) is False (there is no item that is true) and all([]) is True (there is no item that is false). This surprises people, but it is standard logic: "every student in an empty class passed" is true.
any([]) False है (कोई item सच नहीं है) और all([]) True है (कोई item झूठ नहीं है)। यह लोगों को चौंकाता है, पर यह सामान्य तर्क है: "ख़ाली class का हर student पास हुआ" सच है।
any([]) 是 False(没有为真的元素),all([]) 是 True(没有为假的元素)。这常让人意外,但这是标准逻辑:"空班级里的每个学生都及格了"为真。
Proof of Short-CircuitingShort-Circuit का सबूत短路求值的证明
checked = []
def is_big(n):
checked.append(n)
return n > 50
data = [3, 8, 75, 12, 99, 4]
print(any(is_big(n) for n in data), "checked:", checked)
checked.clear()
print(any([is_big(n) for n in data]), "checked:", checked)
Try It — any/all Detectiveकरके देखें — any/all Detective动手试试 — any/all 侦探
Choose the data, the test, any or all, and whether to pass a generator or a list. Press Play and count the checks. The checks shown are the real calls Python made.
Data, जाँच, any या all, और generator या list देना है — चुनें। चलाएँ दबाएँ और जाँचें गिनें। दिखाई गई जाँचें वही असली calls हैं जो Python ने कीं।
选择数据、测试条件、any 或 all,以及传生成器还是列表。点 播放,数一数检查了几次。显示的检查就是 Python 真实发出的调用。
any() stops at the first true item; all() stops at the first false one. On a million items where the answer is at position 3, you pay for 3 checks. But only if you pass a generator: square brackets build the whole list first, so every check runs anyway.
any() पहले सच्चे item पर रुकता है; all() पहले झूठे पर। दस लाख items में अगर जवाब position 3 पर है, तो आप सिर्फ़ 3 जाँचों का ख़र्च देते हैं। पर तभी जब आप generator दें: square brackets पहले पूरी list बनाते हैं, इसलिए हर जाँच फिर भी चलती है।
any() 在第一个真值处停止;all() 在第一个假值处停止。一百万个元素里,如果答案在第 3 个位置,你只需付出 3 次检查的代价。但前提是传入 生成器:方括号会先构建整个列表,所有检查照样都会执行。
min(), max(), sum() — with Keys and Defaults 📏min(), max(), sum() — Keys और Defaults के साथ 📏min()、max()、sum() — 带键与默认值 📏
nums = [3, 7, 1, 9, 4]
print(min(nums), max(nums), sum(nums))
words = ["apple", "kiwi", "blueberry", "fig"]
print(min(words, key=len), max(words, key=len))
students = [{"name": "Aarav", "score": 85},
{"name": "Meera", "score": 92},
{"name": "Kabir", "score": 78}]
top = max(students, key=lambda s: s["score"])
print(f"Top student: {top['name']} with {top['score']}")
print(sum([10.5, 20.5, 30], 100)) # start value
print(sum([])) # empty sum is simply 0
try:
max([]) # but max/min of nothing is an error
except ValueError as e:
print("ValueError:", e)
print(max([], default=0)) # ...unless you give a default
sum([]) is simply 0 — no start value needed. min([]) and max([]) raise ValueError, because there is no smallest or largest of nothing. Pass default= to choose what they return instead. The start argument of sum is for adding to an existing total, not for safety.
sum([]) बस 0 है — start value की ज़रूरत नहीं। min([]) और max([]) ValueError देते हैं, क्योंकि कुछ-नहीं में सबसे छोटा या बड़ा नहीं होता। उनकी जगह क्या लौटे, यह चुनने के लिए default= दें। sum का start argument मौजूदा कुल में जोड़ने के लिए है, सुरक्षा के लिए नहीं।
sum([]) 就是 0 — 不需要初始值。min([]) 和 max([]) 会抛出 ValueError,因为"空"里没有最小或最大。传入 default= 来指定返回值。sum 的 start 参数用于在已有总数上累加,而不是为了安全。
Practical Real-World Examples 🛠️असली दुनिया के उदाहरण 🛠️实用的真实示例 🛠️
Example 1 — Cleaning and Normalising User Inputउदाहरण 1 — User Input की सफ़ाई示例 1 — 清洗并规范用户输入
raw_emails = [" Aarav@Example.com ", "", "MEERA@example.com",
None, " kabir@example.COM"]
# Chain: drop empty/None -> strip -> lowercase
clean = list(map(str.lower, map(str.strip, filter(None, raw_emails))))
print(clean)
# The same as a comprehension
print([e.strip().lower() for e in raw_emails if e])
Both lines give the same result. Nested map(map(filter(...))) is read from the inside out; the comprehension reads left to right. Most Python developers find the second easier.
दोनों lines एक ही नतीजा देती हैं। Nested map(map(filter(...))) अंदर से बाहर पढ़ा जाता है; comprehension बाएँ से दाएँ। ज़्यादातर Python developers को दूसरा आसान लगता है।
两行结果相同。嵌套的 map(map(filter(...))) 要从内往外读;推导式从左往右读。大多数 Python 开发者觉得后者更容易。
Example 2 — Building a Leaderboardउदाहरण 2 — Leaderboard बनाना示例 2 — 制作排行榜
scores = [("Aarav", 85), ("Meera", 92), ("Kabir", 78), ("Diya", 92), ("Isha", 65)]
# Top 3: score high to low, then name A-Z for ties
leaderboard = sorted(scores, key=lambda s: (-s[1], s[0]))[:3]
for rank, (name, score) in enumerate(leaderboard, start=1):
print(f"#{rank} {name:8s} {score}")
Example 3 — Running a Bank Balanceउदाहरण 3 — Bank Balance चलाना示例 3 — 计算银行余额
from functools import reduce
transactions = [
{"type": "credit", "amount": 500},
{"type": "debit", "amount": 120},
{"type": "credit", "amount": 250},
{"type": "debit", "amount": 75},
{"type": "credit", "amount": 1000},
]
credits = sum(t["amount"] for t in transactions if t["type"] == "credit")
balance = reduce(
lambda acc, t: acc + t["amount"] if t["type"] == "credit" else acc - t["amount"],
transactions, 0,
)
print(f"Total credits: Rs {credits}")
print(f"Net balance: Rs {balance}")
The total of credits uses sum() with a generator — clearer than sum(map(..., filter(...))). The balance genuinely needs custom logic (add or subtract), so it is a fair job for reduce. A plain for loop would be just as good.
Credits का कुल generator के साथ sum() इस्तेमाल करता है — sum(map(..., filter(...))) से साफ़। Balance को सच में custom logic चाहिए (जोड़ना या घटाना), इसलिए यह reduce का सही काम है। एक सामान्य for loop भी उतना ही अच्छा होता।
贷方总额用 sum() 配生成器 — 比 sum(map(..., filter(...))) 清晰。余额确实需要自定义逻辑(加或减),所以交给 reduce 很合理。普通的 for 循环也同样好。
Example 4 — Merging Parallel Dataउदाहरण 4 — समानांतर Data को जोड़ना示例 4 — 合并并行数据
ids = [101, 102, 103, 104]
names = ["Aarav", "Meera", "Kabir", "Diya"]
active = [True, False, True, True]
# Build a list of dicts from three parallel lists
users = [{"id": i, "name": n, "active": a} for i, n, a in zip(ids, names, active)]
# Keep only active users
for u in filter(lambda u: u["active"], users):
print(u)
Map/Filter vs Comprehensions — Which to Use? ⚖️Map/Filter बनाम Comprehensions — कौन-सा इस्तेमाल करें? ⚖️Map/Filter 还是推导式 — 用哪个?⚖️
Every map or filter call can be rewritten as a comprehension. Most Python code prefers comprehensions for readability, but the functional form wins in a few cases.
हर map या filter call को comprehension में बदला जा सकता है। ज़्यादातर Python code पढ़ने में आसानी के लिए comprehensions पसंद करता है, पर कुछ मामलों में functional रूप जीतता है।
每个 map 或 filter 调用都能改写成推导式。大多数 Python 代码出于可读性偏爱推导式,但在少数情况下函数式写法更好。
| Featureविशेषता特性 | Behaviourव्यवहार表现 |
|---|---|
| Reads likeऐसे पढ़ा जाता है读起来像 | Apply a function to an iterableIterable पर function लगाओ对可迭代对象应用函数 |
| Lazy?Lazy?惰性? | Yes — returns an iteratorहाँ — iterator लौटाता है是 — 返回迭代器 |
| Best whenसबसे अच्छा जब最适合 | Passing an existing function (str.strip, int)मौजूदा function देना (str.strip, int)传入现成函数(str.strip、int) |
| Nested logicNested logic嵌套逻辑 | Awkward — map(map(...))भद्दा — map(map(...))别扭 — map(map(...)) |
| Featureविशेषता特性 | Behaviourव्यवहार表现 |
|---|---|
| Reads likeऐसे पढ़ा जाता है读起来像 | An English sentenceअंग्रेज़ी का वाक्य一句英语 |
| Lazy?Lazy?惰性? | [...] no; (...) yes[...] नहीं; (...) हाँ[...] 否;(...) 是 |
| Best whenसबसे अच्छा जब最适合 | An inline expression, filter + transform togetherInline expression, filter + transform साथ内联表达式,过滤加转换 |
| Nested logicNested logic嵌套逻辑 | Natural — several for/if partsस्वाभाविक — कई for/if हिस्से自然 — 多个 for/if |
Same Task, Two Stylesएक काम, दो शैलियाँ同一任务,两种风格
nums = [1, 2, 3, 4, 5, 6]
# map + filter - the functional style
result_a = list(map(lambda n: n ** 2, filter(lambda n: n % 2 == 0, nums)))
# List comprehension - the Pythonic style
result_b = [n ** 2 for n in nums if n % 2 == 0]
print(result_a)
print(result_b)
| Situationस्थिति场景 | Recommendationसलाह建议 |
|---|---|
Passing an existing function (str.strip, len, int)मौजूदा function देना (str.strip, len, int)传入现成函数(str.strip、len、int) | map — map(int, parts)map — map(int, parts)map — map(int, parts) |
| A custom inline expressionCustom inline expression自定义内联表达式 | comprehension — [x * 2 for x in nums]comprehension — [x * 2 for x in nums]推导式 — [x * 2 for x in nums] |
| Filter + transform in one passएक बार में filter + transform一次完成过滤和转换 | comprehension — [f(x) for x in it if cond]comprehension — [f(x) for x in it if cond]推导式 — [f(x) for x in it if cond] |
| Several parallel iterablesकई समानांतर iterables多个并行可迭代对象 | map — map(func, a, b), or zip in a comprehensionmap — map(func, a, b), या comprehension में zipmap — map(func, a, b),或在推导式中用 zip |
| Custom accumulationCustom जमा करना自定义累计 | reduce — or a plain for loop for clarityreduce — या साफ़ता के लिए सामान्य for loopreduce — 或为清晰起见用普通 for 循环 |
| Simple sum, min, max, productसीधा sum, min, max, गुणा简单的求和、最小、最大、乘积 | sum / min / max / math.prod — not reducesum / min / max / math.prod — reduce नहींsum / min / max / math.prod — 不用 reduce |
Performance — Are They Faster? ⚡Performance — क्या ये तेज़ हैं? ⚡性能 — 它们更快吗?⚡
A real measurement, 100 runs each over 100,000 numbers. The first three square numbers; the last two convert numbers to text.
असली माप, 100,000 संख्याओं पर हर एक 100 बार। पहले तीन संख्याओं का square करते हैं; आख़िरी दो संख्याओं को text में बदलते हैं।
真实测量:对 100,000 个数,每种写法运行 100 次。前三种求平方,后两种把数字转成文本。
import timeit
setup = "nums = list(range(100_000)); words = [str(n) for n in nums]"
tests = {
"for loop + append": "r = []\nfor n in nums: r.append(n * n)",
"comprehension": "r = [n * n for n in nums]",
"map + lambda": "r = list(map(lambda n: n * n, nums))",
"[str(n) for ...]": "r = [str(n) for n in nums]",
"map(str, ...)": "r = list(map(str, nums))",
}
for name, stmt in tests.items():
t = timeit.timeit(stmt, setup=setup, number=100)
print(f"{name:22} {t:.3f}s")
Squaring (top): the comprehension is fastest. Converting to text (bottom): map(str, ...) beats the comprehension, because it calls the built-in str directly with no lambda in between.
Square करना (ऊपर): comprehension सबसे तेज़ है। Text में बदलना (नीचे): map(str, ...) comprehension को हराता है, क्योंकि यह बीच में बिना lambda के built-in str को सीधे बुलाता है।
求平方(上):推导式最快。转成文本(下):map(str, ...) 胜过推导式,因为它直接调用内置的 str,中间没有 lambda。
For a simple expression, a comprehension wins: map must call your lambda — a full Python function call — for every item, while the comprehension runs the expression inline. map pulls ahead when you pass a built-in such as str, int or len, because those are fast C functions. Your numbers will differ, but the pattern usually holds. Choose for readability first.
सरल expression के लिए comprehension जीतती है: map को हर item के लिए आपका lambda बुलाना पड़ता है — एक पूरी Python function call — जबकि comprehension expression को inline चलाती है। जब आप str, int या len जैसा built-in देते हैं, तो map आगे निकलता है, क्योंकि ये तेज़ C functions हैं। आपके numbers अलग होंगे, पर pattern आमतौर पर वही रहता है। पहले पठनीयता के लिए चुनें।
对于简单表达式,推导式更快:map 要为每个元素调用你的 lambda — 一次完整的 Python 函数调用 — 而推导式是内联执行表达式。当你传入 str、int 或 len 这样的 内置函数 时,map 会领先,因为它们是快速的 C 函数。你的数字会不同,但规律通常一致。首先按可读性来选。
Quick Reference Table 📋झटपट Reference Table 📋速查表 📋
| ToolTool工具 | SignatureSignature签名 | Returnsलौटाता है返回 | Main useमुख्य काम主要用途 |
|---|---|---|---|
lambda | lambda args: expr | Function objectFunction object函数对象 | Small one-expression functionsछोटे एक-expression functions小型单表达式函数 |
map | map(func, *iters, strict=False) | Lazy iteratorLazy iterator惰性迭代器 | Transform each item (strict: 3.14+)हर item बदलना (strict: 3.14+)转换每个元素(strict:3.14+) |
filter | filter(func, iter) | Lazy iteratorLazy iterator惰性迭代器 | Keep matching itemsMatch करने वाले items रखना保留匹配的元素 |
reduce | reduce(func, iter[, start]) | One valueएक value单个值 | Custom accumulation (from functools)Custom जमा करना (functools से)自定义累计(来自 functools) |
zip | zip(*iters, strict=False) | Lazy iterator of tuplesTuples का lazy iterator元组的惰性迭代器 | Pair up parallel iterables (strict: 3.10+)समानांतर iterables की जोड़ी (strict: 3.10+)配对并行可迭代对象(strict:3.10+) |
enumerate | enumerate(iter, start=0) | Lazy iterator of (i, item)(i, item) का lazy iterator(i, item) 的惰性迭代器 | Add a counterCounter जोड़ना添加计数器 |
sorted | sorted(iter, key=None, reverse=False) | New listनई list新列表 | Sort by any key (stable)किसी भी key से sort (stable)按任意键排序(稳定) |
any / all | any(iter) / all(iter) | bool | One / every item true — stop earlyएक / हर item सच — जल्दी रुकना有一个 / 全部为真 — 提前停止 |
min / max | max(iter, key=None, default=...) | One itemएक item单个元素 | Smallest / largest, with optional keyसबसे छोटा / बड़ा, वैकल्पिक key के साथ最小 / 最大,可选键 |
sum | sum(iter, start=0) | Numberसंख्या数字 | Add numbers upसंख्याएँ जोड़ना求和 |
Golden Rules and Quick Quiz 🏆सुनहरे नियम और छोटा Quiz 🏆黄金法则与小测验 🏆
def (PEP 8). Lambdas are for inline use — as arguments to map, filter, sorted, max.def लिखें (PEP 8)। Lambdas inline इस्तेमाल के लिए हैं — map, filter, sorted, max के arguments के रूप में।def(PEP 8)。lambda 用于内联 — 作为 map、filter、sorted、max 的参数。map(lambda ...). It is usually faster and clearer. Use map when you already have a function: map(int, parts).map(lambda ...) की जगह comprehension को तरजीह दें। यह आमतौर पर तेज़ और साफ़ है। जब पहले से function हो, तब map इस्तेमाल करें: map(int, parts)।map(lambda ...)。通常更快也更清晰。已有现成函数时再用 map:map(int, parts)。sum, max, min, any, all, math.prod before reduce. Keep reduce for truly custom accumulation.reduce से पहले sum, max, min, any, all, math.prod देखें। reduce को सच में custom जमा करने के लिए रखें।sum、max、min、any、all、math.prod,再考虑 reduce。把 reduce 留给真正自定义的累计。map, filter and zip return one-shot iterators. Wrap them in list() if you need to use the results twice, index them or print them.map, filter और zip एक-बार वाले iterators लौटाते हैं। नतीजे दो बार इस्तेमाल करने, index करने या print करने हों तो list() में लपेटें।map、filter 和 zip 返回一次性迭代器。需要重复使用、索引或打印结果时,用 list() 包起来。for i in range(len(seq)). Use enumerate for an index and zip to walk two lists together — with strict=True when they must match.for i in range(len(seq)) को बदलें। Index के लिए enumerate और दो lists साथ चलाने के लिए zip इस्तेमाल करें — जब मेल ज़रूरी हो तो strict=True के साथ।for i in range(len(seq))。需要索引用 enumerate,同时遍历两个列表用 zip — 必须等长时加 strict=True。sorted(data, key=lambda s: (-s.score, s.name)). Python's sort is stable, so equal keys keep their order.sorted(data, key=lambda s: (-s.score, s.name))। Python का sort stable है, इसलिए बराबर keys अपना क्रम रखती हैं।sorted(data, key=lambda s: (-s.score, s.name))。Python 的排序是稳定的,相等的键保持原顺序。any and all. any(ok(x) for x in items) stops at the first True; the list version does every check first.any और all को lists नहीं, generators दें। any(ok(x) for x in items) पहले True पर रुकता है; list वाला version पहले हर जाँच करता है।any 和 all 传生成器,而不是列表。any(ok(x) for x in items) 在第一个 True 处停止;列表版本会先做完所有检查。lambda i=i: i. Otherwise every lambda sees the last value.lambda i=i: i। वरना हर lambda आख़िरी value देखता है।lambda i=i: i。否则每个 lambda 看到的都是最后一个值。Quick Quiz — 8 Questionsछोटा Quiz — 8 सवाल小测验 — 8 道题
map transforms, filter selects, reduce combines — and a lambda tells each one what to do. zip pairs, enumerate counts, sorted orders by any key, and any/all stop as soon as they know. Remember that the lazy ones work only once, prefer comprehensions for inline expressions, and let the ready-made built-ins do the common jobs.
map बदलता है, filter चुनता है, reduce मिलाता है — और lambda हर एक को बताता है कि क्या करना है। zip जोड़ी बनाता है, enumerate गिनता है, sorted किसी भी key से क्रम देता है, और any/all जवाब पता चलते ही रुक जाते हैं। याद रखें कि lazy वाले सिर्फ़ एक बार चलते हैं, inline expressions के लिए comprehensions को तरजीह दें, और आम काम तैयार built-ins पर छोड़ दें।
map 负责转换,filter 负责筛选,reduce 负责合并 — lambda 告诉它们各自该做什么。zip 配对,enumerate 计数,sorted 按任意键排序,any/all 一旦知道答案就停止。记住惰性的那些只能用一次,内联表达式优先用推导式,常见任务交给现成的内置函数。