Lesson 02
Lambda Instant Operations — Named, Inline, and Callbacks for Special Functions
Reuse lambda as the FunctionName for special functions: named vs inline, implicit return, ternary max, and a lambda that calls a def helper.
What you will learn
- Why lambdas are instant operations (used at that point, not kept as app APIs)
- How a lambda is still
<class 'function'>like adef - Named lambda vs inline lambda as
FunctionName - Ternary lambdas for max of two, equality, and palindrome
- A lambda that calls a
defhelper when the logic is too big for one expression
This page is the callback lab, not a second copy of Functions → Lambda. Go there for sorted(key=...), immediately invoked lambdas, and the arithmetic toolkit. Stay here for the patterns the SPECIAL FUNCTIONS examples actually pass into filter / map / reduce.
What is a lambda function?
A lambda is an anonymous (unnamed) function used for short, one-line operations. It behaves like a normal function and its type is still function.
Syntax:
lambda parameters: expressionLambda has no return keyword — the expression is returned automatically.
def sumop(a, b):
return a + b
addop = lambda m, p: m + p
print(type(sumop), type(addop)) # both <class 'function'>
print(addop(1000, 2000)) # 3000Do not write return inside a lambda — that is a SyntaxError. Classroom programs often read two numbers with input(). In the playground we pass literals instead.
Why it is called an instant operation
The teaching notes call lambda an instant operation because it is usually created and used only at that moment, instead of being stored as a permanent application function.
The lambda is written inside filter() and is not needed as a named API elsewhere in the program.
Named lambda vs inline lambda
Both approaches perform the same work. The difference is reusability.
| Style | Best for |
|---|---|
| Named | Reusable in multiple places |
| Inline | One-time callbacks |
Named — reuse the same callback twice (positive and negative filters):
positive = lambda val: True if val > 0 else False
negative = lambda val: True if val < 0 else False
pslist = list(filter(positive, lst))
nglist = tuple(filter(negative, lst))Inline — the teaching files collapse that into one line when the lambda is used once:
pslist = list(filter(lambda val: True if val > 0 else False, lst))val > 0 already produces a boolean, so True if val > 0 else False is the explicit classroom form. Both work as FunctionName.
Lambda as a callback
filter(), map(), and reduce() all expect a callback — another function passed as an argument. Lambda fills that first parameter.
list(filter(lambda x: x > 0, lst))The special function owns the loop. Your lambda only answers the one-item question.
Ternary lambda
Lambda supports Python's ternary operator. The lesson finds the maximum of two values and handles equality.
findmaxtwo = lambda m, p: m if m > p else p if p > m else "Both Values are equal"Pattern: lambda a, b: a if a > b else b if b > a else "Equal".
For a list, a lambda can call max / min after checking uniqueness:
findmax = lambda lst: "All Are equal" if len(set(lst)) == 1 else max(lst)len(set(lst)) == 1 means every element was the same.
Palindrome example
A lambda can evaluate strings. The notes check whether a word equals its reverse using slicing.
palindrome = lambda word: "palindrome" if word == word[::-1] else "Not Palindrome"word[::-1]reverses the string- Compare original and reversed values
Lambda returning multiple values
Lambda can return a tuple. The lesson converts days into years, months, and remaining days.
convert_days = lambda days: (days // 365, (days % 365) // 30, (days % 365) % 30)
years, months, leftover = convert_days(800)
# (2, 2, 10)Returned tuple: (years, months, remaining_days). Integer // and % split a day count into years (365), months (30), leftover days.
Lambda calling a normal function
When logic becomes too large (loops, multiple conditions, empty-list checks), write a normal def and let lambda simply call it.
def kvrmax(lst):
if len(lst) == 0:
return "Can't find Max because list is empty"
elif len(set(lst)) == 1:
return "All Values are equal"
maxv = lst[0]
for val in lst:
if val > maxv:
maxv = val
return maxv
findmax = lambda lst: kvrmax(lst)FunctionName is always a callable. The callable can be a lambda that forwards to a named helper.
The same idea appears for sum and average:
def sumavg(lst):
s = 0
for val in lst:
s = s + val
avg = s / len(lst)
return s, avg
findsumavg = lambda lst: sumavg(lst)
ss, av = findsumavg([10, 20, 30, 40])| Size of logic | Choice |
|---|---|
| Small, one expression | Lambda |
Multi-line (loops, several ifs) |
def |
| Need a callable slot | Lambda may be a thin wrapper |
Common mistakes
- Writing
lambda(a, b): a + b— no parentheses around the parameter list - Putting
returnin a lambda - Using a lambda for a multi-line search loop — extract a
def - Forgetting that
type(lambda x: x)is stillfunction, not a speciallambdatype
Interview cheat sheet
| Concept | Answer |
|---|---|
| Lambda | Anonymous one-line function |
| Return | Implicit (automatic) |
| Type | function |
| Named lambda | Reusable callback |
| Inline lambda | Used once inside filter / map / reduce |
| Best use | Short single-expression operations |
Practice in the playground
- Call
findmaxtwowith(7, 7)— you should see the equality message. - Change
convert_daysto use a 28-day month and re-run800. - Pass an empty list into
findmax_manual.
Next: filter().
Loading playground…
Check your understanding
Lambda callbacks quiz
What is `type(addop)` when `addop = lambda m, p: m + p`?
1 / 10