Anonymous Functions: Create, Bind, and Call

An anonymous function is a function written without a declared function name. It lets you express a short computation as a value that you can store and call. This lesson uses Python, where the lambda keyword creates anonymous functions. The central distinction is between producing a function and executing its computation: these happen at different times.

Write the function as an expression

Python uses this syntax:


Python
lambda parameters: expression


A parameter appears before the colon. The function body is the expression after the colon. When you call the function, Python binds the supplied arguments to its parameters, evaluates the body, and returns its value automatically.


For a one-parameter function whose body represents an expression EE, the governing idea is:


f(a)=E(a)f(a) = E(a)


Here, E(a)E(a) means evaluating the expression with the parameter bound to the argument aa. Other names in the expression follow Python's scope rules.


Example: The expression lambda x: x + 2 produces a function that adds two to its argument. Calling that function with 6 returns 8.


A function may have several parameters, such as lambda x, y: x + y, or no parameters, such as lambda: 7. A conditional expression also fits: lambda x: 0 if x < 0 else x returns zero for negative inputs and otherwise returns the input.



Separate creation from calling

Evaluating a lambda expression produces a function object. Assigning that value to a variable gives you a way to refer to it; it does not execute the body. The body runs when the function is called.


Python
f = lambda x: x + 2
result = f(6)


The first line creates a function and binds f to it. The second line calls that function and binds result to the returned integer, 8.


A flowchart separates creation of an anonymous function from evaluation of its expression during a call.


The following operations illustrate three different uses of assignment. Read the rows in order.


Operation

What happens

Does the body run?

f = lambda x: x + 2

Creates a function and binds f to it

No

f(6)

Calls the function and returns 8

Yes

g = f

Binds g to the same function object

No

f = lambda x: x * 3

Creates another function and rebinds f

No


After the final row, g still refers to the original function. Thus, g(5) returns 7, while f(5) returns 15. Reassigning one variable does not rewrite the function referenced by another variable.

Track surrounding names and defaults

Parameters are local to each call. Names in the body that are not parameters are resolved through the surrounding scope. In these module-level examples, an external name refers to its current global binding when the body executes.


Python
rate = 3
charge = lambda amount: rate * amount
rate = 5


Calling charge(4) now returns 20. Creating the function did not freeze the external value of rate.


A default argument value supplies a parameter when the caller omits that argument. In Python, default argument expressions are evaluated when the function is created.


Python
rate = 3
estimate = lambda amount, rate=rate: rate * amount
rate = 5


Now estimate(4) returns 12: its local parameter rate receives the stored default value 3. An explicit call such as estimate(4, 6) instead returns 24, because the supplied argument replaces that default for this call.



What to remember

  • A lambda expression produces a function value.
  • Calling the function binds arguments and evaluates its body.
  • Assigning another name to a function does not call or copy its computation.
  • Surrounding names and stored defaults can behave differently when settings change.

Example: Convert Sensor Counts with Anonymous Functions

A laboratory sensor reports integer counts. Use an anonymous function, a function written without a declared name, to subtract an offset and convert the remaining counts to millivolts. In this module-level Python program, offset is measured in counts and scale is measured in mV per count. The code stores their numerical values:


Python
offset = 8
scale = 4
convert = lambda raw: scale * (raw - offset)


Treat all values as exact. Perform the parts in order, keeping changes made in earlier parts.


a) What does the third line assign to convert, and what voltage does convert(23) return?


The third line creates a function object and assigns that object to convert. Assigning the function does not evaluate its body. No converted voltage is produced until a call occurs.


The call convert(23) binds the local parameter raw to 23 counts. The body reads the current external values: an offset of 8 counts and a scale of 4 mV per count. The offset-corrected reading is ________.


corrected reading=23 counts−8 counts=15 counts\text{corrected reading} = 23\ \text{counts} - 8\ \text{counts} = 15\ \text{counts}


Multiply that corrected reading by the scale:


V=(4 mVcount)(15 counts)=60 mVV = \left(4\ \frac{\text{mV}}{\text{count}}\right)(15\ \text{counts}) = 60\ \text{mV}


Thus, convert stores a function, and convert(23) returns the numerical value 60, representing 60 mV.


b) The program next executes offset = 11. What voltage does another call to convert(23) return?


The reassignment changes the global value of offset. The body of convert reads this surrounding name when the call occurs; creating the function earlier did not store the old offset as a default.


The new call again binds raw to 23 counts. The corrected reading is now ________.


corrected reading=23 counts−11 counts=12 counts\text{corrected reading} = 23\ \text{counts} - 11\ \text{counts} = 12\ \text{counts}


The scale is still 4 mV per count:


V=(4 mVcount)(12 counts)=48 mVV = \left(4\ \frac{\text{mV}}{\text{count}}\right)(12\ \text{counts}) = 48\ \text{mV}


The call returns 48 mV. Increasing the subtracted offset reduced the converted voltage, which is consistent with the expression.


c) With the global offset still 11, the program creates another function:


Python
local_convert = lambda raw, offset: scale * (raw - offset)


What voltage does local_convert(23, 5) return, and which offset does its body use?


This function has two parameters. The call binds raw to 23 counts and its local parameter offset to 5 counts. That local parameter takes precedence over the global variable with the same name. The call does not change the global offset of 11 counts.


The corrected reading is ________:


corrected reading=23 counts−5 counts=18 counts\text{corrected reading} = 23\ \text{counts} - 5\ \text{counts} = 18\ \text{counts}


The name scale is not a parameter, so the body reads its external value of 4 mV per count.


V=(4 mVcount)(18 counts)=72 mVV = \left(4\ \frac{\text{mV}}{\text{count}}\right)(18\ \text{counts}) = 72\ \text{mV}


The call uses the supplied 5-count offset and returns 72 mV.

An online shop calculates a packing charge in cents using the following Python function. Which anonymous function accepts the same single argument and returns the same charge for every nonnegative integer items?


Python
def packing_charge(items):
    return 120 + 35 * items
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A networking program uses an anonymous function to calculate a message size. Consider the following Python statement:


Python
total = (lambda header, records: records * 16 + header)(24, 7)


What value is assigned to total? Answer in bytes, to the nearest integer.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A library's booking program uses the following Python anonymous function to compute an additional charge in cents for a given number of scanned pages:


Python
overage = lambda pages: 0 if pages <= 40 else 6 * (pages - 40)


Complete the table with the value returned for each page count. Enter exact integer charges in cents.

Pages scannedAdditional charge (cents)
36
40
43
47

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors