1

I am a new to programming, and was looking for some help with adding multiple expressions to a lambda function. But cannot seem to get to work. It's a noob level problem, so can please some one help me out?

a = int()
b = int()

greater (a,b) = lambda(a,b): (a > b) == 'a' or (b > a) == 'b' :

print (greater(10,9))
4
  • 1
    Keep in mind this violates the Python style guide (PEP8). At this point you might as well define this function with def Commented Aug 12, 2020 at 18:54
  • 1
    hi, i understand def is the way to go. I was just going through the concept of lambda functions, and wanted to perform a simple operation. Commented Aug 12, 2020 at 18:56
  • https://docs.python.org/3/reference/expressions.html#lambda Commented Aug 12, 2020 at 19:05
  • See also Is there a way to perform “if” in python's lambda Commented Aug 12, 2020 at 19:23

1 Answer 1

3

You can achieve this using an if condition (which will not "catch" the case a and b are equal):

greater = lambda a, b: 'a' if a > b else 'b'

Catching the equality case is a bit tricker and requires nested if:

greater = lambda a, b: 'a' if a > b else 'b' if b > a else 'N/A'

(Note that there are no parenthesis after greater and around the lambda's arguments)

However, this violates the Python style guide (PEP8). At this point (where you already named the lambda), you should just define this function with def.

Sign up to request clarification or add additional context in comments.

12 Comments

I'd rather specify this as a ternary operation of some sorts... a traditional if statement does not operate this way and doesn't return a value
hi i just executed your expression, but it's still giving me a syntax error. ok I'll tell you the actual question.Create a lambda function 'greater', which takes two arguments x and y and return x if x>y otherwise y.
in the second case I would use brackets, otherwise it is not obvious which condition executes first
@Dan Since this piece of code shouldn't be used anyway, I don't think that really matters
@MZ I'm not sure what you mean by "a traditional if statement does not operate this way and doesn't return a value"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.