What exactly is "lambda" in Python?

Question:

I want to know what exactly is lambda in python? and where and why it is used.
thanks

Asked By: Hossein

||

Answers:

The first linked returned by googling “python lambda” points to a page whose first paragraphs answer your question. I could copy & paste the content it, but I think it’s unfair 🙂

Answered By: MarcoS

It’s an inline anonymous function.

Answered By: recursive

lambda is an anonymous function, usually used for something quick that needs computing.

Example (This is used in a LexYacc command parser):

assign_command = lambda dictionary, command: lambda command_function: dictionary.setdefault(command, command_function)

This is a decorator. Put before a command we’d have from the LexYacc parser:
@assign_command(_command_handlers, 'COMMAND')

This essentially builds a python script from the LexYacc language defined.

Or, a bit simpler:

`x = lambda x: return x > 0 and x & (x-1) == 0

Answered By: TyrantWave

lambda allows you define simple, unnamed functions inline with your code, e.g. as an argument. This is useful if you plan to use the function only once, and therefore don’t want to clutter your code with a named function.

Let’s say you have a list of numbers (thelist), and you want to get a list of the same length, with each number doubled. Rather than defining a times_two function, you could do something like this:

map(lambda x: x * 2, thelist)

lambda also makes Currying more convenient.

Answered By: AndreiM

Lambda is more of a concept or programming technique then anything else.

Basically it’s the idea that you get a function (a first-class object in python) returned as a result of another function instead of an object or primitive type. I know, it’s confusing.

See this example from the python documentation:

def make_incrementor(n):
  return lambda x: x + n
f = make_incrementor(42)
f(0)
>>> 42
f(1)
>>> 43

So make_incrementor creates a function that uses n in it’s results. You could have a function that would increment a parameter by 2 like so:

f2 = make_incrementor(2)
f2(3)
>>> 5

This is a very powerful idea in functional programming and functional programming languages like lisp & scheme.

Hope this helps.

Answered By: Dave

Lambda functions are not a Python specific concept, but are a general programming term for anonymous function, i.e. functions without a name. In Python they are commonly used where you need to pass a simple function as a parameter to another function.

The sort method on lists takes a parameter key which is a function that is used to calculate the value the list is sorted on. Imagine you are sorting a list of two element tuples, and you want to sort the list based on the first element. You need to pass a function to key which returns the first element. You could do this:

def first_element(x):
    return x[0]
my_list.sort(key=first_element)

or, much more concisely you can do:

my_list.sort(key=lambda x: x[0])
Answered By: Andrew Wilkinson

The lambda construct is a shorter way to define a simple function that calculates a single expression. The def statement can be inconvenient and make the code longer, broken up and harder to read through. The functions created by the two are virtually the same by the way they work, the difference is that lambda is limited to a single expression the value of which is returned and that def assigns a name to the function and adds it to the local variables by that same name. Also lambda can be used in an expression directly, while def is a statement.

def f(x, y):
    return x + y

Would give you almost the same result as

f = lambda x, y: x + y

And you can use it directly in an expression

g(5, 6, helper=lambda x, y: x + y)

which with def would be less concise

def helper_function(x + y):
    return x + y

g(5, 6, helper=helper_function)
Answered By: Rosh Oxymoron

lambda is a way of defining an anonymous in-line function to accomplish some task versus defining it with the def keyword and calling it. Think of it as a shorthand you can use when you won’t need to reuse a function. Anywhere you use lambda, you could substitute an explicitly called function: it’s use is completely optional and left to the programmer as a matter of coding style.

Example code (without lambda):

def numSquared(num):
    return num**2

for i in range(1,11):
    print numSquared(i)

Example code (with lambda):

for i in range(1,11):
    print (lambda x: x**2)(i)

A good beginner’s discussion of lambda:
DiveIntPython.org – Lambda

Answered By: chucksmash

Lambdas are not anonymous functions. Lambdas are anonymous expressions.

They’re accessed like functions, but they’re not the same thing. Functions allow complex tasks: flow control, variable declarations and lists of statements containing expressions. Expressions are merely one part of a function, and that’s what lambdas give you. They’re severely limited compared to functions.

Python does not support anonymous functions. For examples of languages that do, see Javascript and Lua.

(Note: It’s correct to call lambdas anonymous functions in functional languages, where the mathematical definition of “function” is used, but in procedural languages the word has a very different meaning than in mathematics.)

Answered By: Glenn Maynard

Lambda can be interpreted intuitively as algebra function.

Suppose a basic algebra y = x**2 + 1
if typed directly,

>>> y = x**2 + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

error occurs and reports that variable ‘x’ should be defined firstly.
nevertheless,’x’ is unknown, how can it be pre-defined.

Lambda helps:

python
>>> y = lambda x: x**2 + 1  # no errors reports
>>> y(3)
10

That’s core about lambda,

It’s in programming language to write an inline function.

Answered By: AbstProcDo

Lambda is an anonymous function in Python programming language, instead of bearing a def statement in the front it is simply called and written lambda.

def mult2(x):
    return x*2

print(mult2(2))

# returns 4

Exactly same you can do with a lambda function.

lam = lambda x : x*2
print(lam(2))

# returns 4
For more details you can look up in this blog post.
http://friendlypython.herokuapp.com/2017/1/anonymous-function-lambda/ or here

Answered By: JSalys

I would like to explain this with a little layman approach in terms of the usage perspective, since all the technical points are already covered.

A lambda function is just like any other function, only thing that makes it different (other than the syntax and the fact that it can’t be reused), is that it is used when we want to quickly write a function which takes an argument and just returns a value using only one expression.

For instance:
If all that a function does is take a argument and add 1 to it then using a lambda function is a better approach than a normal function.
But if your function requires more than one line of processing before returning the value, then we need to use a normal function definition and then call it.

Answered By: preetika mondal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.