0

Question: Create a lambda function 'greater', which takes two arguments x and y and return x if x>y otherwise y.

If x = 2 and y= 3, then the output should be 3. Input: 9,3 Expected Output: 9

Answer:

f(a,b)=lambda x :a if a>b else b     #code written here

f(9,3) #input

Error message:

  File "<ipython-input-30-a6687330a9f4>", line 11

f(a,b)=lambda x :a if a>b else b
                                    ^
SyntaxError: can't assign to function call
SuperStormer
  • 4,997
  • 5
  • 25
  • 35

2 Answers2

0

f(a,b) is calling f which does not exist yet and you try to assign a function to it, but the function cannot be assigned to a call but only a name f alone.

If you wanted to assign it you would instead use:

f = lambda x :a if a>b else b

But this is not a good way to define a function it is against the style guide, see: Is it pythonic: naming lambdas and https://www.python.org/dev/peps/pep-0008/#programming-recommendations, and instead use:

def f(x):
    return a if a > b else b

However, there are many errors in both of these codes. To answer the question you want:

lambda x, y: x if x > y else y

You can assign that to a name using def if you would like:

def f(x,y):
    return x if x > y else y

Then you could call:

a = 2
b = 3
print(f(a,b))

Output (as expected):

3
Eli Harold
  • 2,280
  • 1
  • 3
  • 22
0

You cannot assign a value to a function call

Instead, you can define your lambda function like this:

f=lambda a,b:a if a>b else b

And You can call this function using the name f and passing the parameters (a,b):

print(f(2,5))
  • You definitely should not assign the function like this, see: https://stackoverflow.com/questions/38381556/is-it-pythonic-naming-lambdas and https://www.python.org/dev/peps/pep-0008/#programming-recommendations. – Eli Harold Feb 03 '22 at 14:48
  • 1
    definitely, the sole purpose of using a lambda function gets destroyed by assigning it, But here what the guy meant to use was this statement but unfortunately with an erroneous syntax ... It might be the case if It has to be used with pandas dataframe or something which is not specified. Therefore, I mentioned what he required. Thanks for the correction though! – Khushi Bhambri Feb 03 '22 at 14:53