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
Cet exercice fait partie du cours
Python for R Users
Instructions
- Convert the
sq_func()regular function into a lambda function and call itsq_lambda. - Use the lambda function to print the results when
3is passed into the function.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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(____(____))