Wednesday, November 11, 2020

Python Lambda Function

Python Lambda Function


What is a Lambda function?


Lambda function is an anonymous function with 1 line expression.


format: lambda <parameters> : expression


A simple example:
> lambda x : x
⇒ function lambda


This function is same as:

def same(x):
    return x

This function just return the parameter pass in to the function.

Access lambda function without a function name:
> (lambda x:x)(5) ⇒ 5

Exercise


How to convert the following function to lambda?

def square(n):
    return n*n

> square= lambda n : ???
> square(5) ⇒ 25

List order with lambda


> fruits=[('apple',3),('orange',2),('lemon',1)]
> sorted(fruits)
⇒ [('apple', 3), ('lemon', 1), ('orange', 2)]

How to sort by order of the id at the back?

> sorted(fruits,key=fruit_order)
def fruit_order(item):
    return item[1]  # return the id of the fruit

Can use a lambda function to replace the fruit_order() function.

> sorted(fruits,key=lambda x:x[1])
⇒ [('lemon', 1), ('orange', 2), ('apple', 3)]