Functions, scope and lambda
Functions in Python: definitions, parameters vs arguments, return values, scope (LEGB), local/global/nonlocal, first-class and higher-order functions, lambdas and closures, default/variable arguments, annotations, and common pitfalls.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Functions let you break a large problem into clear, reusable pieces, so code is easier to test, maintain, and share. Understanding scope and lambda expressions helps you control variable lifetimes, avoid bugs, and write concise, expressive code for tasks like data processing, signal analysis, or quick GUI callbacks.
Key ideas
- Argument: The actual value (or object) passed to a parameter during a function call.
- Return value: The value a function sends back to the caller using
return. If noreturnis executed, the return value isNone. - Function definition: The creation of a function using
def name(parameters):followed by an indented block. - Function call: Executing a function by using its name followed by parentheses, optionally with arguments.
- Docstring: A string literal placed as the first statement in a function body that documents what the function does.
- Annotation: Optional metadata for parameters and return value, written after
:and->. They do not change runtime behavior but can be used by tools and IDEs. - Default argument: A parameter value specified in the function definition; if the caller omits that argument, the default is used.
- Variable-length arguments: Mechanisms to accept many arguments:
*argscollects extra positional arguments into a tuple;**kwargscollects extra keyword arguments into a dictionary. - Keyword argument: An argument passed by name, e.g.,
area(radius=2), which matches the parameter by name rather than position. - Positional-only parameter: A parameter that must be supplied by position, indicated before
/in a function signature. - Keyword-only parameter: A parameter that must be supplied by name, indicated after
*in a function signature. - Scope: The textual region of a program where a name (variable, function) is visible and can be used.
- Lifetime: The period during which an object exists in memory. Scope is about visibility; lifetime is about existence.
- LEGB rule: The exact name-resolution order Python uses: Local → Enclosing → Global → Built-in.
- Local: names assigned inside the current function.
- Enclosing: names in any enclosing function’s scope (for nested functions).
- Global: names assigned at the top level of the module.
- Built-in: names in Python’s built-in namespace (e.g.,
len).
- Local variable: A name bound inside a function without
globalornonlocal; it is visible only within that function. - Global variable: A name bound at module level. Within a function, assignment to it requires
globalto refer to the module-level name. - nonlocal declaration: A keyword used inside an inner function to rebind a variable from the nearest enclosing (but non-global) function scope.
- First-class function: A function treated like any other object: can be assigned to a variable, passed as an argument, or returned from another function.
- Higher-order function: A function that takes functions as arguments and/or returns a function.
- Lambda (anonymous function): A small, unnamed function defined with
lambda parameters: expression. It must contain a single expression and returns the expression’s value. - Closure: A function object that remembers values from its enclosing scope even after that scope has finished executing.
- Pure function: A function with no side effects that always returns the same output for the same inputs. While good for reasoning, not all useful functions can be pure.
Exact statements and commonly asked derivations/points:
- Definition of a function (exam style): “A function in Python is a named, reusable block of code defined using
def, which may accept arguments (parameters) and may return a value usingreturn.” Assumption: Python interpreter executes top-to-bottom; function body runs only when called. - LEGB Rule (exam statement): “Python resolves identifiers using the Local, Enclosing, Global, Built-in order. First the current function’s local scope is searched; next any enclosing function scopes; then the module’s global scope; finally the built-in namespace.” Assumption: the code may have nested functions; built-ins are available via the interpreter’s environment.
- Global and nonlocal (exam statement): “Inside a function,
global xdeclares that assignments toxrefer to the module-level variable;nonlocal xdeclares that assignments toxrefer to the nearest enclosing function’sx.” Assumptions: The declared name must exist at the respective outer scope fornonlocal; forglobal, the name is in the module’s global namespace (it may be created by assignment after declaration). - Default argument evaluation (exam statement): “Default argument expressions are evaluated once at function definition time, not each call.” Assumption: Module is executed once; the same default object is reused across calls. Consequence: using a mutable default like
[]can accumulate state across calls. - Lambda restriction (exam statement): “A lambda contains a single expression; no statements are allowed inside
lambda.” This is a Python language rule; it applies across standard Python implementations. - Closures (exam reasoning): An inner function references names from its enclosing scope; when returned, it carries those bindings, forming a closure. Derivation sketch: define outer with local
x; inner usesx; return inner; call returned function later; it still seesxbecause the interpreter keepscellreferences to enclosing variables.
Diagram to draw for scope (if asked):
- Draw three nested rectangles labeled from inner to outer: “Local (current function)”, “Enclosing (outer function)”, “Global (module)”, and note “Built-in” outside all as a cloud. Inside each, write example names: local:
a, temp; enclosing:outer_var; global:PI, operations; built-in:len, print. Add an arrow from a name lookup in local going outward to show the LEGB search path.
Formulas
Since this is a programming topic, this section lists syntax to remember.
def name(parameters):— define a function namedname.parametersare comma-separated. Body is an indented block.return expression— exits the function and returns the value ofexpression. BarereturnreturnsNone.def f(a, b=2):— default argument:bdefaults to 2 if not passed.def f(*args, **kwargs):— variable-length:argsis a tuple of extra positional args;kwargsis a dict of extra keyword args.def f(a, /, b, *, c):— positional-only parameters before/; keyword-only after*.def f(x: int) -> int:— annotations: parameterxhas annotationint; return value annotatedint."""Docstring text"""— put as the first statement inside a function to document it.global name1, name2— declare names as global inside a function to rebind module-level variables.nonlocal name1, name2— declare names from the nearest enclosing function’s scope to rebind them.lambda parameters: expression— anonymous function returning the expression’s value.map(function, iterable, ...)— appliesfunctionto items from one or more iterables (stops at the shortest); returns an iterator.filter(function, iterable)— keeps elements wherefunction(element)is truthy; returns an iterator.sorted(iterable, key=function, reverse=False)— returns a new sorted list;keycomputes a sort key.
Worked examples
Example 1: Functions and scope (local vs global) Complete Python program:
# Program: sum of two integers and counting operations using a global variable
operations = 0 # global counter at module level
def add(a, b):
"""Return the sum of a and b."""
return a + b
def record_operation():
global operations # rebind the global name
operations += 1
# Read two integers from input and use the functions
# Input format: two integers separated by space
nums = input().strip().split()
a = int(nums[0])
b = int(nums[1])
s = add(a, b)
record_operation()
print("Sum:", s)
print("Operations:", operations)
Sample input:
3 5
Exact output:
Sum: 8
Operations: 1
Explanation: operations is defined globally and modified inside record_operation() using global. Without global, operations += 1 would try to assign to a local name and raise UnboundLocalError.
Example 2: Lambda with map, filter, and sorted Complete Python program:
# Program: read a list, keep even numbers, square them, and sort descending using lambdas
# Input format:
# n (number of integers)
# a1 a2 ... an
n = int(input().strip())
nums = list(map(int, input().strip().split()))
# Ensure we only use the first n numbers even if more are given
nums = nums[:n]
# Keep even numbers
evens = list(filter(lambda x: (x % 2) == 0, nums))
# Square them
squares = list(map(lambda x: x * x, evens))
# Sort descending
sorted_desc = sorted(squares, key=lambda x: x, reverse=True)
print("Evens:", evens)
print("Squares:", squares)
print("Sorted:", sorted_desc)
Sample input:
6
1 2 3 4 5 6
Exact output:
Evens: [2, 4, 6]
Squares: [4, 16, 36]
Sorted: [36, 16, 4]
Explanation: filter uses a lambda predicate for evenness; map applies a lambda to square; sorted uses reverse=True for descending order.
Example 3: Closures and nonlocal Complete Python program:
# Program: make a counter closure with configurable start and step
def make_counter(start=0, step=1):
count = start
def inc():
nonlocal count # rebind the enclosing variable
count += step
return count
return inc
# Input format:
# start step
# m (number of increments to print)
vals = input().strip().split()
start = int(vals[0])
step = int(vals[1])
m = int(input().strip())
c = make_counter(start, step)
for _ in range(m):
print(c())
Sample input:
10 5
3
Exact output:
15
20
25
Explanation: The inner function inc closes over count. The nonlocal keyword allows inc to rebind the count from the enclosing scope. Successive calls remember and update the previous value.
Common mistakes
- Shadowing built-ins or globals unintentionally (e.g.,
len = 5), which breaks later calls tolen(). - Assuming lambda can contain statements or multiple expressions;
lambdamust be a single expression. - Late binding in lambdas within loops:
funcs = [lambda: i for i in range(3)]returns functions that all use the finali(2). Solution: capture as defaultlambda i=i: i. - Forgetting to call a function (printing the function object): writing
print(f)instead ofprint(f()). - Misplacing the docstring: it must be the first statement in the function body to be recognized as a docstring.
- Confusing parameter vs argument names; or mixing up order when using positional arguments. Prefer keywords to avoid mistakes.
- Not handling the number of inputs correctly when using
input().split()andmap(int, ...), leading toValueErroror truncated lists. - Overusing
globalfor data that should be passed as parameters or returned; this harms testability. - Forgetting
nonlocalin closures when intending to modify the enclosing variable; results in a new local variable orUnboundLocalError. - Assuming
mapandfilterreturn lists in Python 3; they return iterators. Wrap withlist(...)to realize them.
For your exam
- Programs: Write a function to compute something (e.g., factorial, GCD) and demonstrate correct scope handling. Ensure complete code: input reading, function definition, correct returns, and exact output formatting.
- Diagrams: Scope diagram showing Local, Enclosing, Global, Built-in, with arrows indicating name resolution. Label each region and example names.
- Reasoning/derivation style questions: Explain LEGB rule step-by-step on a given snippet. Explain why lambdas in loops capture the final value and how to fix using default arguments.
- Best practices: Show preference for pure functions where possible, passing data via parameters and return values instead of globals; use keyword arguments for readability; keep lambdas short and readable.
- For full marks: Correct syntax, correct explanation of LEGB, accurate code with no runtime errors, and if asked, clear diagram description with labels. If the question mentions “explain with an example”, include a small working snippet and expected output.
Quick check
- State the LEGB rule and give one example of a name found in each of the four scopes.
- Why is
def f(x, lst=[]): lst.append(x); return lstusually a bad idea? Show a corrected version. - Write a one-line lambda that returns the last two digits of an integer n as a positive number.
Answers: 1) Name resolution order is Local → Enclosing → Global → Built-in. Example names: Local: i inside a function; Enclosing: total in an outer function used by an inner; Global: PI at module top; Built-in: len. 2) The default list is evaluated once and reused across calls, accumulating values unexpectedly. Correct: def f(x, lst=None): lst = [] if lst is None else lst; lst.append(x); return lst. 3) lambda n: abs(n) % 100.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?