Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate35 min
Lambda instant operations for special functions

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 a def
  • Named lambda vs inline lambda as FunctionName
  • Ternary lambdas for max of two, equality, and palindrome
  • A lambda that calls a def helper 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.

Normal function and lambda both return 300

Syntax:

python
lambda parameters: expression

Lambda has no return keyword — the expression is returned automatically.

python
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))  # 3000

Do 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.

Inline lambda inside filter executes then returns

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.

Named lambda versus inline lambda
Style Best for
Named Reusable in multiple places
Inline One-time callbacks

Named — reuse the same callback twice (positive and negative filters):

python
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:

python
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.

Lambda callback passed into filter
python
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.

Ternary lambda returns the larger of 10 and 20
python
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:

python
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.

madam compared with its reversed slice is a palindrome
python
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.

800 days split into years months leftover days
python
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.

Lambda wrapping kvrmax to get a maximum
python
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:

python
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 return in a lambda
  • Using a lambda for a multi-line search loop — extract a def
  • Forgetting that type(lambda x: x) is still function, not a special lambda type

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

  1. Call findmaxtwo with (7, 7) — you should see the equality message.
  2. Change convert_days to use a 28-day month and re-run 800.
  3. 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