Functions and Lambdas for Data Work
Every week the bookshop wants the same numbers: revenue per sale, with a discount on big orders. You could retype the arithmetic each time, or name it once and reuse it everywhere. In data work, that named recipe is a function, and short throwaway recipes are lambdas.
The rule
Name a recipe you repeat; use a lambda for a one-line recipe you pass along.
A function takes inputs, does work, and returns a result:
def revenue(copies, price, discount=0.0):
return copies * price * (1 - discount)
revenue(3, 250) # 750.0
revenue(5, 400, discount=0.1) # 1800.0discount=0.0 is a default: callers may leave it out. Passing it by name, discount=0.1, is a keyword argument, and it makes calls easier to read.
Sometimes you do not know how many inputs will arrive:
def total(*amounts, **options):
result = sum(amounts)
if options.get("round_to"):
result = round(result, options["round_to"])
return result
total(750, 2000, 800) # 3550*amounts gathers extra positional values into a tuple; **options gathers extra keyword values into a dict. The names args and kwargs are only a habit; the stars do the work.
A lambda is a function with no name and a single expression, written where it is used:
by_price = sorted(books, key=lambda b: b["price"])You will pass lambdas constantly in pandas, for example to sort or transform values.
The shortcut
Ask "Will I reuse this, or does it need more than one line?" Either answer yes: write a def with a clear name. Both no: a lambda inline is fine.
Spot the repetition
The shop applies "10% off when 5 or more copies" in three different reports.
The trap is packing logic into a long lambda because it feels clever. If you have to read it twice, it deserves a def.
Drills
Answer fast — trust the rule.
What does revenue(2, 400) return with the revenue function above?
Inside def f(*args):, what type is args when you call f(1, 2, 3)?
Inside def g(**kwargs):, what is kwargs after g(city="Pune", top=3)?
What does (lambda x: x * 2)(21) evaluate to?
Which recipe is the best fit for a lambda?
Remember
- Name a recipe you repeat; use a lambda for a one-line recipe you pass along.
*argsbecomes a tuple,**kwargsbecomes a dict; defaults make arguments optional.- If a lambda needs a second read, turn it into a named
def.
