MCS 260 Fall 2021
The built-in function
sum(L) takes an iterable
L and returns the sum of all its elements.
Previously (Lec 20): functions are values
Functions can take other functions as arguments
def dotwice(f): """Call the function f twice (with no arguments)""" f() f()
A function that accepts function arguments is sometimes called a higher-order function.
announce_call(f) that calls a given function
f, but prints a message before and after.
A function that loops from 0 to 100, but accepts a function to increment the value.
nest(func,val,times) that applies function
func a specified number of times to
nest(f,x,3)should return the value of
next(h,y,2)should return the value of
repeat_until_acceptable(getval,testfn) that calls
getval repeatedly until the return value is one for which
In Python, you can create a function with no name using the syntax:
lambda x: x*x # param x, return value x*x lambda x,y: x-y # params x and y, return value x-y
lambda gives you the function object, so the value of
lambda x,y: x-y
is the same as the value of
if you previously defined
def diff(x,y): return x-y
Functions definitely deserve names if they are used in several places, or if they are complicated.
lambda is good for simple functions used once, so the definition appears in the only place of use.
The built-in functions
list.sort accept a keyword argument
that is a function which is applied to elements before making comparisons.
L is a list of words, then
max(L,key=len) is the longest word.