Adam_G
Adam_G

Reputation: 7879

Python: Lambda Inside Print Function

There are many questions related to lambda and printing, but I could not find anything about this exact question.

I'd like to print the results of my lambda function within a print statement. However, I am getting the wrong output. I am using Python 3

from __future__ import print_function
file_name = "tester"
target = "blue"
prediction = "red"

print(file_name,target,prediction, str(lambda x: print('+') if target==prediction else print('-')))

This returns:

tester blue red <function <lambda> at 0x10918c2f0>

How do I get the actual results of the lambda function?

Upvotes: 2

Views: 3846

Answers (2)

VelikiiNehochuha
VelikiiNehochuha

Reputation: 4373

just call lambda

print(file_name,target,prediction, (lambda: '+' if target==prediction else '-')())

Upvotes: -1

thefourtheye
thefourtheye

Reputation: 239593

lambdas are actually functions only. So, unless you invoke them you will not get any result from them. When you do

str(lambda x: print('+') if target==prediction else print('-'))

you are not actually invoking the lambda function, but trying to get the string representation of the function itself. As you can see, the string representation has the information about what the object is and where it is stored in memory.

<function <lambda> at 0x10918c2f0>

Apart from that, the other problem in your lambda is, you are actually invoking print function in it. It will actually print the result but return None. So, even if you invoke the lambda expression, you will get None printed. For example,

>>> print(print("1"))
1
None

But, the good news is, in your case, you don't need lamda at all.

print(file_name, target, prediction, '+' if target == prediction else '-')

The expression,

'+' if target == prediction else '-'

is called conditional expression and will make sure that you will get + if target is equal to prediction, - otherwise.

>>> file_name, target, prediction = "tester", "blue", "red"
>>> print(file_name, target, prediction, '+' if target == prediction else '-')
tester blue red -

Note: If you are using Python 3.x, you don't need to import print_function from the __future__. It already is a function, in Python 3.x.

Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type(print)
<class 'builtin_function_or_method'>

Upvotes: 7

Related Questions