Python : What is Lambda Function / Expression

# Lambda Expression
function_label = lambda input : output      (return expression / computation)
>> square = lambda num: num**2

# Normal function
def square(num): return num**2

Can be called as >> square(2)

NOTE : lambda's body is a single expression, not a block of statements.

The small methods which has computation logic of expression like convert currency, temp etc can be easily converted into lamda.

For Example

def convertDollarFunction(rate, quantity) : return rate * quantity;
convertDollarLambda = lambda rate, quantity : rate * quantity;


Python supports a style of programming called functional programming where you can pass functions to other functions to do stuff. Example:

mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])

sets mult3 to [3, 6, 9], those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than

def filterfunc(x):
    return x % 3 == 0
mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])

lambda expressions really shine when used in conjunction with map(),filter() and reduce().

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s