Python Lambda


Introduction


  • Lambda is a special type of Python function that have limited capabilities.
  • A function that will be used only once in your program. These functions are called anonymous or unbound functions.

Syntax
lambda arguments: expression


  • Lambda functions can accept zero or more arguments but only one expression
  • Here return statement is implicit.
  • Lambda function can be declared and invoke together also
(lambda x, y: x + y)(5, 3)

What kind of things can I, and can I not, put into a lambda? 

Don't or Limitations

  • If it doesn’t return a value, 
  • If it isn’t an expression and can’t be put into a lambda
  • You can only use expressions, but not statements.
  • lambda function with multiple lines/expressions/statements is not possible
  • You cannot declare and use local variables.
Do
  • If you can imagine it in an assignment statement, on the right-hand side of the equals sign, it is an expression and can be put into a lambda.
  • lambda can be member of list, dictionary 
  • You can only use one expression.

Use cases

1. map and reduce Python built-in function
2. filter Python built-in function
3. sort and sorted Python built-in function
4. Print formating
5. Use in WhLambda functions can accept zero or more arguments but only one expressionile statement. 
6. if for loop is invoking a function, then it can replaced with map. 


Multiple expressions

Use tuples, and implement your own evaluation order
If you are a coward and fear that evaluation order will change in a future release of python, 

you can use eval
map(eval,("f1()","f2()",...,"fn()"))

You can also use apply
map(lambda x:apply(x,()),(f1,f2,f3))

General Notes
  • One can pass functions as arguments to other functions
  • A function can be the return value of another function.
  • The expression returns (or evaluates to) a value, whereas a statement does not. 
Reference 

https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/
http://p-nand-q.com/python/lambda.html
https://www.bogotobogo.com/python/python_functions_lambda.php

0 comments:

Post a Comment