Python Lambda functions
A lambda function is a (usually small) function that is defined without a name. A lambda function is declared as an expression and then either assigned to a variable or passed as a parameter to another function.
lambda arguments: expression
my_function = lambda x : x.capitalize()
Here we define a function and assign that function to a variable. Everything in Python is just
an object, and a function is no different and can be assigned to variables and passed to other
functions. So a lambda function is simply a function that is not defined using
def and has no name. It's an Anonymous function.
character = 'a' my_function(character)
Lambda functions usually get passed to other functions. Here's an example. Say you had a list of values and you wanted to do something to each value, but that 'something' changed depending on what you needed. You could do achieve that using a lambda function:
def modify_array(value_array, lambda_function) """This method modifies each entry in the array by applying lambda_function""" return [ lambda_function(value) for value in value_array ] myList = ['a', 'b', 'c'] # capitalize each item in the array values = modify_array(myList, lambda x : x.capitalize()) print(values) # output will be ['A', 'B', 'C'] # duplicate each item in the array values = modify_array(myList, lambda x : x + x) print(values) # output will be ['aa', 'bb', 'cc']
In each case we called the same
modify_array method, but passed in a different
lambda function to perform an operation inside the modify_array function.