filmov
tv
Python lambda Functions - Work with anonymous functions

Показать описание
What are lambdas or anonymous functions?
Anonymous functions also know as lambdas are functions that behave like regular functions buy are by default not reusable. Lambda functions are small and usually are written in one single line.
Lambdas structure include the following elements:
- Keyword: lambda
- Variables: any number of named variables (example: x, y, z)
- Expression: calculation to be executed by the function.
# before we start let's create a regular function
def add_one(a):
return + 1
l# if we pass a 2 as value, it returns 3
add_one(2)
////3
# let's do the same using lambda
(lambda a: a + 1)(2)
////3
# we can assign lambdas to variables
add_one_lambda = lambda a : a + 1
add_one_lambda(2)
////3
# let's see another example
multiply = lambda a, b : a * b
multiply (2,3)
////6
list (map (lambda x:x**2, [2,3,4,5]))
///[4, 9, 16, 25]
In conclusion: Lambdas or anonymous functions are a clever and pythonic way to create functions where when reusability is less important that readability.
#python #data #lambda #functions
Anonymous functions also know as lambdas are functions that behave like regular functions buy are by default not reusable. Lambda functions are small and usually are written in one single line.
Lambdas structure include the following elements:
- Keyword: lambda
- Variables: any number of named variables (example: x, y, z)
- Expression: calculation to be executed by the function.
# before we start let's create a regular function
def add_one(a):
return + 1
l# if we pass a 2 as value, it returns 3
add_one(2)
////3
# let's do the same using lambda
(lambda a: a + 1)(2)
////3
# we can assign lambdas to variables
add_one_lambda = lambda a : a + 1
add_one_lambda(2)
////3
# let's see another example
multiply = lambda a, b : a * b
multiply (2,3)
////6
list (map (lambda x:x**2, [2,3,4,5]))
///[4, 9, 16, 25]
In conclusion: Lambdas or anonymous functions are a clever and pythonic way to create functions where when reusability is less important that readability.
#python #data #lambda #functions