Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lambda expression

Tags:

python

lambda

Consider the following:

>>> a=2
>>> f=lambda x: x**a
>>> f(3)
9
>>> a=4
>>> f(3)
81

I would like for f not to change when a is changed. What is the nicest way to do this?

like image 485
laurt Avatar asked Nov 27 '13 13:11

laurt


People also ask

What is the lambda expression in Python?

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

How do you write a lambda expression in Python?

A Python lambda function behaves like a normal function in regard to arguments. Therefore, a lambda parameter can be initialized with a default value: the parameter n takes the outer n as a default value. The Python lambda function could have been written as lambda x=n: print(x) and have the same result.

What can I use instead of lambda in Python?

One of good alternatives of lambda function is list comprehension. For map() , filter() and reduce() , all of them can be done using list comprehension. List comprehension is a solution between a regular for-loop and lambda function.


2 Answers

You need to bind a to a keyword argument when defining the lambda:

f = lambda x, a=a: x**a

Now a is a local (bound as an argument) instead of a global name.

Demo:

>>> a = 2
>>> f = lambda x, a=a: x**a
>>> f(3)
9
>>> a = 4
>>> f(3)
9
like image 61
Martijn Pieters Avatar answered Oct 23 '22 08:10

Martijn Pieters


Another option is to create a closure:

>>> a=2
>>> f = (lambda a: lambda x: x**a)(a)
>>> f(3)
9
>>> a=4
>>> f(3)
9

This is especially useful when you have more than one argument:

 f = (lambda a, b, c: lambda x: a + b * c - x)(a, b, c)

or even

 f = (lambda a, b, c, **rest: lambda x: a + b * c - x)(**locals())
like image 41
georg Avatar answered Oct 23 '22 09:10

georg