Scope, Callbacks, and Lambdas
Lesson 25 of 48 in Coddy's Python for JavaScript Developers course.
Pass a transformation into a function while keeping local assignments separate from changes to caller-owned data.
JavaScript
function announce(value, render) {
console.log(render(value));
}
announce(7, value => "Room " + value);Python
def announce(value, render):
print(render(value))
announce(7, lambda value: "Room " + str(value))What changes
Both programs print Room 7. A function is a value you can pass to another function. Here the callback receives a room number and returns display text. The outer function prints that returned text. Python lambda creates a small function from one expression; use def when you need statements or several steps. A parameter name is local to its call. Reassigning that name does not rebind the caller's variable, while appending through a list parameter mutates the shared list. Reading a module-level name is allowed, but assigning a name inside a function normally makes it local throughout that function. Use explicit parameters and returns to avoid hidden dependencies. global permits rebinding a module-level name. In a nested function, nonlocal instead refers to a previously bound name in an enclosing function scope.
Common mistake
Pass a function value as the callback, rather than calling the function early without its required argument. A Python lambda cannot contain a statement block like a JavaScript arrow function can.
Your task
Apply a supplied callback to each value and return a new list. The locked driver also verifies that the original list is unchanged.
Challenge
BeginnerImplement transform_all(values, transform). Call the supplied one-argument function exactly once per list element, in encounter order, and return a new list of its results. Preserve values. Do not print. The locked driver reads integer tokens on one line. It calls your function with two different callbacks: adding 3 and negating. It prints both result lists, then both callback counts on one line. Next it prints True if both callbacks received exactly the original elements in order, and finally unchanged or changed for the input list.
Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.
Try it yourself
from functions import transform_all
values = [int(part) for part in input().split()]
before = values.copy()
plus_calls = []
negative_calls = []
def plus(value):
plus_calls.append(value)
return value + 3
def negative(value):
negative_calls.append(value)
return -value
print(transform_all(values, plus))
print(transform_all(values, negative))
print(len(plus_calls), len(negative_calls))
print(plus_calls == before and negative_calls == before)
print("unchanged" if values == before else "changed")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules5Functions and Scope
Define and ReturnPositional and Keyword ArgsExtra Arguments and UnpackingScope, Callbacks, and LambdasRecap: Refactor a Pricing Tool3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler