Lambda Function Call [duplicate] - python

This question already has answers here:
What do lambda function closures capture?
(7 answers)
Closed 3 years ago.
The following is a code snippet which I don't seem to get. The question is how to make the function output the desired result (not mentioning what the desired result is, I assume its printing 0 to 9).
Here is the question:
What does the below code snippet print out? How can we fix the anonymous functions to behave as we'd expect?
functions = []
for i in range(10):
functions.append(lambda : i)
for f in functions:
print(f())

In Python, no new scope will be produced in for loop
So after for i in range(10), the variable i is still exist, and its value == 9. And the lambda function lambda : i access the variable i
In order to output your desired result, you should pass the variable as a function argument in loop
functions = []
for i in range(10):
functions.append(lambda i=i: i)
for f in functions:
print(f())

Related

What is the use of '#f' in python? [duplicate]

This question already has answers here:
What does the "at" (#) symbol do in Python?
(14 answers)
How do I make function decorators and chain them together?
(20 answers)
Closed 26 days ago.
#the code given is:
def f(a):
print('hello')
#f
def f(a,b):
return a%b
f(4,0)
What I expected to happen was a zero division error, instead it printed hello.
When I write the same code without '#f'
it gives the expected result as output
I've never seen symbol/expression being used in python
This is new and Google too has nothing about it
Decorator syntax is a shorthand for a particular function application.
#f
def f(a, b):
return a%b
is roughly equivalent to
def tmp(a, b):
return a % b
tmp2 = f(tmp)
f = tmp2
(Reusing the name f for everything makes this tricker to understand.)
First, your division-by-zero function is defined. Next, your original function f is called: it prints hello and returns None. Finally, you attempt to call None with two arguments, but it isn't callable, resulting in the TypeError you allude to.
In short, the decorator syntax takes care of treating all the things that would otherwise have been named f as distinct objects and applying things in the correct order.

Lambda function is outputting memory address instead of actual values [duplicate]

This question already has answers here:
Python lambda function printing <function <lambda> at 0x7fcbbc740668> instead of value
(5 answers)
Closed 7 months ago.
when i run the code i get a memory location as an output
<function at 0x00000200FF8A5E50>
val = (lambda colmns:(colmns.max + colmns.min)/2
print(val)
A lambda is just an anonymous function object and that's why it prints that way. In fact, as soon as you assign it to a variable... then why have a lambda in the first place? Might as well do
def foo(colmns):
return (colmns.max + colmns.min)/2
And then it wouldn't be too surprising that print(foo) is <function 0x...>.

Question caused by lambda expression in python? [duplicate]

This question already has answers here:
How does a lambda function refer to its parameters in python?
(4 answers)
Closed 1 year ago.
I wrote a Python code like:
fun_list = []
for i in range(10):
fun_list.append(lambda : f(i))
for j in range(10):
fun_list[j]()
I want it to output numbers from 0 to 9, but actually it outputs 9 for ten times!
I think the question is that the variable is be transported into function f only it was be called. Once it was be called it will globally find variable named 'i'.
How to modify the code so that it can output numbers from 0 to 9?
Your Code doesn't make sensefun_list[j]() how are you calling a List Element?
If You Want to append the numbers mentioned above into your array then Correct Code is:-
fun_list = []
for i in range(10): ### the range has to be from 0 to 10 that is [0,10)
fun_list.append(i) ### You dont need lambda function to append i
What This does is also if of No need because you first of all havent initialized what is f?... Is it a function?. You here are not appending the value but instead appending the called function statement. You dont need that. Just do it simply like above....:-
fun_list.append(lambda : f(i))

Explain this particular python lambda expression [duplicate]

This question already has answers here:
Accessing elements of Python dictionary by index
(11 answers)
Closed 4 years ago.
Iam trying to learn lambda expressions and came across the below :
funcs = {
idx: lambda: print(idx) for idx in range(4)
}
funcs[0]()
did not understand what is meant by funcs[0] ? Why the index and 0 ?
This is a cool example to show how binding and scope work with lambda functions. As Daniel said, funcs is a dictionary of functions with four elements in it (with keys 0,1,2 and 3). What is interesting is that you call the function at key 0, you expect the index (idx) that was used to create that key to then print out and you'll get 0. BUT I believe if you run this code, you actually print 3! WHAT!?!? So what is happening is that the lambda function is actually not binding the value of 0 when it stores the reference to the function. That means, when the loop finishes, the variable idx has 3 associated with it and therefore when you call the lambda function in position 0, it looks up the reference to the variable idx and finds the value 3 and then prints that out. Fun :)
That was referring more to your question title than to the test... The 0 is to access the function that has key 0 in the dictionary.

Different iterators are giving me different answers [duplicate]

This question already has answers here:
Creating functions (or lambdas) in a loop (or comprehension)
(6 answers)
What do lambda function closures capture?
(7 answers)
Closed 9 years ago.
What is the difference between
for i in range(0,3): print cons[i]['fun'](x0)
and
for f in cons: print f['fun'](x0)
where cons is defined as following
A = np.asmatrix([[1,0,0],[0,1,0],[0,0,1]])
x0 = np.asarray([1,2,0])
cons = list()
for i in range(0,3): cons.append({'fun':lambda x: np.dot(A[i],x)})
Your problem probably is related to the fact that you are having a lambda clause using an unbound variable (i). Change your code like this:
for i in range(0,3): cons.append({'fun':lambda x, i=i: np.dot(A[i],x)})
(I. e. just insert that , i=i.)
This way the value of i is part of the lambda clause and not taken from the surrounding scope.

Categories