Lambda Expressions

In python functions are defined using def keyword and the name of the function. After defining python allocates memory using the name and can be reused number of times based on the requirement. Python offers anonymous functions which can be used only once. These anonymous functions without out any name are referred as lambda expressions and can be defined using lambda keyword.


The syntax of the lambda expressions is as follows

lambda x: x 


As mentioned, lambda expressions are used when you can define an expression or statements without any name.

names = ["Jeff Bezos", "Mark Zuckerberg", "Elon Musk", "Bill Gates", "Ratan Tata"]

sorted(names, key=lambda name: name.split()[1])

OUTPUT ['Jeff Bezos', 'Bill Gates', 'Elon Musk', 'Ratan Tata', 'Mark Zuckerberg'] 

In the above example, we sorted the list of method using the last name with the help of sorted inbuilt method and passing the lambda expression as key attribute.

Leave a Reply