Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference for python between lambda and regular function?

Tags:

python

lambda

I'm curious about the difference between lambda function and a regular function (defined with def) - in the python level. (I know what is the difference for programmers and when to use each one.)

>>> def a():     return 1  >>> b = lambda: 1 >>> a <function a at 0x0000000004036F98> >>> b <function <lambda> at 0x0000000004031588> 

As we can see - python knows that b is a lambda function and a is a regular function. why is that? what is the difference between them to python?

like image 519
slallum Avatar asked Sep 04 '12 13:09

slallum


People also ask

Is lambda the same as function?

Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).

What is the purpose of lambda function in Python?

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 the benefit of lambda in Python?

The lambda keyword in Python provides a shortcut for declaring small anonymous functions. Lambda functions behave just like regular functions declared with the def keyword. They can be used whenever function objects are required.

Is lambda function faster than regular function?

Lambda functions are inline functions and thus execute comparatively faster.


1 Answers

They are the same type so they are treated the same way:

>>> type(a) <type 'function'> >>> type(b) <type 'function'> 

Python also knows that b was defined as a lambda function and it sets that as function name:

>>> a.func_name 'a' >>> b.func_name '<lambda>' 

In other words, it influences the name that the function will get but as far as Python is concerned, both are functions which means they can be mostly used in the same way. See mgilson's comment below for an important difference between functions and lambda functions regarding pickling.

like image 145
Simeon Visser Avatar answered Oct 06 '22 15:10

Simeon Visser