+8

What is lambda in python ???

5/15/2019 12:59:18 PM

Abhishek Gupta

6 Answers

New Answer

+11

A lambda statement is used to create new function objects. the lambda takes a parameter followed by a single expression only which becomes the body of the function and the value of this expression is returned by the new function. E.g. Lambda p = [{'x': 5, 'y': 3}, {'x': 4, 'y': 1}] p.sort(key=lambda i: i['y']) print(p) Output : [{'y': 1, 'x': 4}, {'y': 3, 'x': 5}] we want to do a custom sort, and for that we need to write a function but instead of writing a separate def block for a function that will get used in only this one place, we use a lambda expression to create a new function. so lambdas are use to reduce the time to make another function using def and use that. it easily works with filter map and other functions very easily. https://www.sololearn.com/learn/Python/2460/?ref=app https://www.sololearn.com/Discuss/1036672/?ref=app https://www.sololearn.com/Discuss/1675905/?ref=app https://stackoverflow.com/questions/890128/why-are-python-lambdas-useful

+5

Here is an very good article regarding this https://medium.com/@happymishra66/lambda-map-and-filter-in-python-4935f248593 https://stackoverflow.com/questions/890128/why-are-python-lambdas-useful

+3

https://code.sololearn.com/c8J8ASFl4z9B/?ref=app

+2

lambda is a keyword used to create functions much like def. Often it is recommended to use def to define functions, but there are special cases where lambda definitions are useful.

0

lambda is used to create anonymous functions, usually these are the one liner function which can be called from some other function.