Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "lambda" mean in Python, and what's the simplest way to use it?

Tags:

python

lambda

Can you give an example and other examples that show when and when not to use Lambda? My book gives me examples, but they're confusing.

like image 488
TIMEX Avatar asked Oct 18 '09 00:10

TIMEX


People also ask

What is lambda in Python how is it used?

We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter() , map() etc.

What is lambda why it is used?

Lambda runs your code on a high-availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, and logging.


2 Answers

Lambda, which originated from Lambda Calculus and (AFAIK) was first implemented in Lisp, is basically an anonymous function - a function which doesn't have a name, and is used in-line, in other words you can assign an identifier to a lambda function in a single expression as such:

>>> addTwo = lambda x: x+2
>>> addTwo(2)
4

This assigns addTwo to the anonymous function, which accepts 1 argument x, and in the function body it adds 2 to x, it returns the last value of the last expression in the function body so there's no return keyword.

The code above is roughly equivalent to:

>>> def addTwo(x):
...     return x+2
... 
>>> addTwo(2)
4

Except you're not using a function definition, you're assigning an identifier to the lambda.

The best place to use them is when you don't really want to define a function with a name, possibly because that function will only be used one time and not numerous times, in which case you would be better off with a function definition.

Example of a hash tree using lambdas:

>>> mapTree = {
...     'number': lambda x: x**x,
...     'string': lambda x: x[1:]
... }
>>> otype = 'number'
>>> mapTree[otype](2)
4
>>> otype = 'string'
>>> mapTree[otype]('foo')
'oo'

In this example I don't really want to define a name to either of those functions because I'll only use them within the hash, therefore I'll use lambdas.

like image 148
meder omuraliev Avatar answered Oct 20 '22 21:10

meder omuraliev


I do not know which book you are using, but Dive into Python has a section which I think is informative.

like image 36
Sinan Ünür Avatar answered Oct 20 '22 21:10

Sinan Ünür