Lambda functions
If you have ever used the *apply
family of functions (such as sapply()
and lapply()
) in R,
there's a good chance you might have used anonymous functions. Anonymous functions in Python are known as lambda functions.
These functions are not too different from a regular function.
The keyword in a lambda function is lambda
instead of def
.
These functions are typically used for functions that are 'one-line' long.
For example, a function that returns the cube of a number can be written as:
cube_lambda = lambda x: x**3
print(cube_lambda(3))
27
This exercise is part of the course
Python for R Users
Exercise instructions
- Convert the
sq_func()
regular function into a lambda function and call itsq_lambda
. - Use the lambda function to print the results when
3
is passed into the function.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# A function that takes a value and returns its square
def sq_func(x):
return(x**2)
# A lambda function that takes a value and returns its square
sq_lambda = ____ ____: ____
# Use the lambda function
print(____(____))