-1

I have changed my question a bit, I think my question was not clear before. Apologies!!!

I have mentioned two cases below: one with lambda function and the other with a user defined function.

Case 1: Using a lambda function.

[lambda i: i*2  for i in range(4) ]

The output is the list of 4 same functions as given below:

[<function __main__.<listcomp>.<lambda>(i)>,
 <function __main__.<listcomp>.<lambda>(i)>,
 <function __main__.<listcomp>.<lambda>(i)>,
 <function __main__.<listcomp>.<lambda>(i)>]

Case 2: Using a user defined function

def func(x):
   return(x*2)

[func(i)  for i in range(4) ]

The output here is as intended.

[0, 2, 4, 6]
Anurag
  • 13
  • 4
  • 2
    It's unclear to me what you're asking. You're not *calling* the lambda in the list comprehensions, so you build a list *of lambdas*. – jonrsharpe Dec 22 '18 at 11:24
  • 1
    Nothing seems wrong here - the expression with `lambda:` is a function, so if you create four of them with your comprehension, you get four functions in a list; if you apply it to a column, it gets applied. If you want to do the calculation in the comprehension, `[i*2 for i in range(4)]` will work. – Jim Danner Dec 22 '18 at 11:26
  • Case 1 and 2 are identical substitute regardless of "i" or "x" used. This has nothing to do with pandas or data-science. At case 3 you start something but did not finish it properly. Include a descent example if you want to talk about theory. – ZF007 Dec 22 '18 at 11:30
  • 1
    Does `[(lamvda .,,)(x) for x ...]` work? – hpaulj Dec 22 '18 at 11:44
  • Possible duplicate of [Python: Lambda function in List Comprehensions](https://stackoverflow.com/questions/6076270/python-lambda-function-in-list-comprehensions) – n1tk Dec 22 '18 at 12:31
  • `your lambda function doesn’t call the function. Is creating 4 different lambda functions, as you see on your output, and put all those in a list ` – n1tk Dec 22 '18 at 12:37
  • `[(lambda i: i*2)(i) for i in range(4)]` is how should work ... – n1tk Dec 22 '18 at 12:44

1 Answers1

3

Your difference is because

lambda i: i*2 

is a function definition, not a function call. To see this, do

func = lambda i: i*2 
print(func)

So your list comprehension is defining 4 identical functions. But you want to define one function and call it 4 times. This will work:

[(lambda x: x*2)(i)  for i in range(4) ]

Compare that with:

[func(i)  for i in range(4) ]

and you will see that (lambda x: x*2) is the equivalent of func. The identifier func is the name of a function that you have defined before, and (lambda x: x*2) is an expression that defines the function in-line.

Here x is the parameter to the lambda function (just as it is in func) and i is the value you are calling that function with.

But that is a very complicated way to to things. Defining a lambda function made it hard for you to see what was wrong, and hard for others to see what your intent was.

BoarGules
  • 16,440
  • 2
  • 27
  • 44