What is lambda in Python?

I want to know what is lambdain python? and where and why it is used. thank

+5
source share
10 answers

Lambda is more a concept or programming technique than anything else.

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

This example is provided in the python documentation :

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

Thus make_incrementor creates a function that uses n in the results. You may have a function that would increase the parameter by 2 like this:

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

, lisp .

, .

+6

Lambdas . Lambdas - .

, . : , , . - , , . .

Python . . Javascript Lua.

(: lambdas , "", , .)

+6

lambda , , , . . , , , .

, (thelist), , . times_two - :

map(lambda x: x * 2, thelist)

lambda Currying .

+2

- Python , , . Python , .

sort key, , , . , . key, . :

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

, :

my_list.sort(key=lambda x: x[0])
+2

lambda - , . def , . , , , , lambda , , def . lambda , def - .

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

,

f = lambda x, y: x + y

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

def

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

g(5, 6, helper=helper_function)
+2

lambda - - def . , , . , , : .

( ):

def numSquared(num):
    return num**2

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

( ):

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

lambda: DiveIntPython.org - Lambda

+2

, googling "python lambda", . , :)

+1

.

0

lambda - , - , .

( LexYacc):

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

. , LexYacc: @assign_command(_command_handlers, 'COMMAND')

python script LexYacc.

, :

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

0

.

Suppose that the 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

an error occurs and reports that the variable x must first be defined. however, the "x" is not known how it can be determined in advance.

Lambda helps:

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

This is the core of lambda,

In a programming language for writing an inline function.

0
source

All Articles