Reading preferences
Concept

Arguments, Lambda, and Recursion

Understand how calls bind arguments and how recursive calls return.

python, functions, arguments, lambda, recursion

How a call supplies information

Arguments can be matched by position or by parameter name. A default is used when no value is supplied. In a definition, *args gathers extra positional arguments in a tuple and **kwargs gathers extra keyword arguments in a dictionary. The names args and kwargs are conventions, not special words.

Python illustration

def total_to(n):
    if n == 0:
        return 0
    return n + total_to(n - 1)

def describe(name, label="reader", *scores, **details):
    return name, label, scores, details

print(total_to(3))
print(describe("Ada", "learner", 4, 5, active=True))
print(describe(name="Lin"))

Prepared output — not live execution:

6
('Ada', 'learner', (4, 5), {'active': True})
('Lin', 'reader', (), {})

The recursive example expects a non-negative integer. Each call waits for the smaller call, then adds its own n; zero is the stopping case.

See the reasoning

Follow the example one step at a time

Trace total_to(3) down to its base case and back to the caller. This is a prepared teaching demonstration, not live code execution.

Call with 3

total_to(3) → 3 + total_to(2)

The call cannot finish until the smaller call returns.

Make calls predictable

Defaults are evaluated when the function is defined, not on every call. Avoid a mutable default such as items=[] when calls need independent lists: use items=None and create a list inside when items is None. In a signature / marks preceding parameters positional-only; parameters after * are keyword-only. Invalid or duplicate bindings raise TypeError.

def scale(value, /, factor=2, *, offset=0):
    return value * factor + offset

print(scale(3, offset=1))  # 7

Here value must be positional; factor may be positional or keyword; and offset must be a keyword. For example, scale(value=3) raises TypeError. Pass *values or **mapping in a call to unpack arguments; the same symbols in a definition collect arguments.

A lambda is a small anonymous function containing one expression, for example sorted(words, key=lambda word: len(word)). Prefer a named def when a function needs a meaningful name, multiple statements, or explanation. Recursion uses call stack space and Python has a recursion limit; an iterative solution may be more suitable for large inputs. See Recursion for the general reasoning.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. When is a default argument expression evaluated?
2. In greet(name="Ada"), how is the argument supplied?
3. What does **kwargs collect in a function definition?
4. Why does a recursive function need a reachable base case?

References and further reading