How does 'lambda variable=variable: somefunction()' work? [duplicate] - python

This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
What do lambda function closures capture?
(7 answers)
Closed 6 months ago.
I was searching Stack Overflow for a solution to a problem of mine when I stumbled upon this user submitted solution (to someone else's question):
appsMenu.add_command(label=app, command=openApp(Apps[app]))
Command parameters that call functions need to be wrapped in a lambda, to prevent them from being called right away. Additionally, commands bound within a for loop need the looping variable as a default argument, in order for it to bind the right value each time.
appsMenu.add_command(label=app, command=lambda app=app: openApp(Apps[app]))
As you can see, the user wrote lambda app=app, and for the love of me I cannot figure out why. What does it do?

The lambda expression is used to define a one-line (anonymous) function. Thus, writing
f = lambda x: 2*x
is (more or less) equivalent to
def f(x):
return 2*x
Further, as for normal functions, it is possible to have default arguments also in a lambda function. Thus
k = 2
f = lambda x=k: 2*x
can be called either as f() where x will be the value of k i.e. 2 or as f(3) where x = 3. Now, to make it even more strange, since the lambda function has its own name space, it is possible to exchange the k with x as
x = 2
f = lambda x=x: 2*x
which then means that the default value of f() will be the (outer) x value (i.e. 2) if no other parameter is set.
Thus, the expression
lambda app=app: openApp(Apps[app])
is a function (unnamed) that takes one argument app with the default value of the (outer) variable app. And when called, it will execute the instruction openApp(Apps[app]) where Apps is a global (outer) object.
Now, why would we want that, instead of just writing command=openApp(Apps[app]) when calling .add_command()? The reason is that we want the command to execute not when defining the command, i.e., when calling .add_command(), but at a later time, namely when the menu item is selected.
Thus, to defer to the execution we wrap the execution of openApp(Apps[app]) in a function. This function will then be executed when the menu item is selected. Thereby we will call openApp then, instead of right now (at the time we want to add the command) which would be the case otherwise.
Now, since the lambda function is called with no arguments, it will use its default parameter (outer) app as (inner) app. That makes the whole argument a bit redundant, as the outer variable is directly accessible within the lambda expression. Therefore, it is possible to simplify the expression to lambda: openApp(Apps[app]) i.e. wiht no arguments, making the full line
appsMenu.add_command(label=app, command=lambda: openApp(Apps[app]))
To me, this looks a bit simpler, and is the way I would write it, but conceptually there is no difference between this and the code with default parameters.

Related

Basic Python function statements [duplicate]

This question already has answers here:
What is `lambda` in Python code? How does it work with `key` arguments to `sorted`, `sum` etc.?
(4 answers)
Closed 6 months ago.
I want to know what exactly is lambda in python? and where and why it is used.
thanks
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.
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.)
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])
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)
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
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.
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 :)
It's an inline anonymous function.
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
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.
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
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.

Strange behavior when passing a function as second parameter of the `setdefault` dictionary method [duplicate]

This question already has an answer here:
Why does setdefault evaluate default when key is set?
(1 answer)
Closed 6 months ago.
I don't understand the behavior of setdefault in this scenario:
def f(x):
return x+1
dct = {5: 15}
print(dct.setdefault(5, f(5)))
The key 5 is in the dictionary, but instead of returning the value 15 immediately, it wastes time computing the function at the second argument. In the end, it discards the output of f and returns 15.
Is this a bug? What is its purpose?
Python allows you to use expressions as parameters to a function. In fact, you could view all parameters as expressions. Python will evaluate all of the parameter expressions from left to right, resolving each to a single object. A function object is created, the list is expanded into the parameter set for the function, and finally the function is called.
In dct.setdefault(5, f(5)), python has no idea whether a function parameter expression will be used or not. And it can't evaluate the expression after the call is made. So, f(5) is resolved and the function is called.
If a function is expensive, then setdefault is not the tool for you. Use "not in" instead.
if 5 not in dct:
dct[5] = f(5)
In Python all arguments must be evaluated before the function is called. It would be a 'performant' behavior for this case, but could lead to consistency issues for others.

What is the syntax behind the sorted argument? [duplicate]

This question already has answers here:
What is `lambda` in Python code? How does it work with `key` arguments to `sorted`, `sum` etc.?
(4 answers)
Closed 6 months ago.
I want to know what exactly is lambda in python? and where and why it is used.
thanks
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.
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.)
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])
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)
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
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.
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 :)
It's an inline anonymous function.
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
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.
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
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.

Python lambda's binding to local values [duplicate]

This question already has answers here:
Creating functions (or lambdas) in a loop (or comprehension)
(6 answers)
Closed 6 months ago.
The following code spits out 1 twice, but I expect to see 0 and then 1.
def pv(v) :
print v
x = []
for v in range(2):
x.append(lambda : pv(v))
for xx in x:
xx()
I expected python lambdas to bind to the reference a local variable is pointing to, behind the scenes. However that does not seem to be the case. I have encountered this problem in a large system where the lambda is doing modern C++'s equivalent of a bind ('boost::bind' for example) where in such case you would bind to a smart ptr or copy construct a copy for the lambda.
So, how do I bind a local variable to a lambda function and have it retain the correct reference when used? I'm quite gobsmacked with the behaviour since I would not expect this from a language with a garbage collector.
Change x.append(lambda : pv(v)) to x.append(lambda v=v: pv(v)).
You expect "python lambdas to bind to the reference a local variable is pointing to, behind the scene", but that is not how Python works. Python looks up the variable name at the time the function is called, not when it is created. Using a default argument works because default arguments are evaluated when the function is created, not when it is called.
This is not something special about lambdas. Consider:
x = "before foo defined"
def foo():
print x
x = "after foo was defined"
foo()
prints
after foo was defined
The lambda's closure holds a reference to the variable being used, not its value, so if the value of the variable later changes, the value in the closure also changes. That is, the closure variable's value is resolved when the function is called, not when it is created. (Python's behavior here is not unusual in the functional programming world, for what it's worth.)
There are two solutions:
Use a default argument, binding the current value of the variable to a local name at the time of definition. lambda v=v: pv(v)
Use a double-lambda and immediately call the first one. (lambda v: lambda: pv(v))(v)

What exactly is "lambda" in Python? [duplicate]

This question already has answers here:
What is `lambda` in Python code? How does it work with `key` arguments to `sorted`, `sum` etc.?
(4 answers)
Closed 6 months ago.
I want to know what exactly is lambda in python? and where and why it is used.
thanks
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.
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.)
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])
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)
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
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.
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 :)
It's an inline anonymous function.
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
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.
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
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.

Categories

Resources