Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is "lambda" in Python?

Tags:

python

lambda

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

like image 836
Hossein Avatar asked Mar 08 '11 14:03

Hossein


People also ask

What does lambda in Python do?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

What is the purpose of lambda?

Lambda runs your code on high availability compute infrastructure and performs all the administration of your compute resources. This includes server and operating system maintenance, capacity provisioning and automatic scaling, code and security patch deployment, and code monitoring and logging.

What is lambda in simple terms?

00:05 A lambda function is a simple, short, throwaway function which is designed to be created inline in code. They're also known as lambda expressions, anonymous functions, lambda abstractions, lambda form, or function literals.

Why is it called lambda Python?

The term “Lambda” comes from mathematics, where it's called lambda calculus. In programming, a Lambda expression (or function) is just an anonymous function, i.e., a function with no name. In fact, some Lambda expressions don't even have a function body.


2 Answers

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.

like image 200
Dave Avatar answered Sep 24 '22 03:09

Dave


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.)

like image 27
Glenn Maynard Avatar answered Sep 22 '22 03:09

Glenn Maynard