24

I am trying to use 3 if statements within a python lambda function. Here is my code:

y=lambda symbol: 'X' if symbol==True 'O' if symbol==False else ' '

I Have been able to get two if statements to work just fine e.g.

x=lambda cake: "Yum" if cake=="chocolate" else "Yuck"

Essentially, I want a lambda function to use if statements to return 'X' if the symbol is True, 'O' if it is false, and ' ' otherwise. I'm not even sure if this is even possible, but I haven't been able to find any information on the internet, so I would really appreciate any help :)

asked Oct 30, 2015 at 15:23
4
  • If symbol is a boolean, it can only have two values. What could ever trip the last else? Commented Oct 30, 2015 at 15:26
  • 2
    @ddsnowboard almost anything which is not a boolean. Commented Oct 30, 2015 at 15:31
  • @bereal So the idea is that symbol could be of any type? Commented Oct 30, 2015 at 15:35
  • @bereal is right, I have a list which contains True, False, or None. I want my code to convert None to ' ', so None would trip this else statement. I can understand why you might have found this confusing though, because it does seem like symbol is a Boolean without any context from the rest of my code. Commented Oct 30, 2015 at 15:36

3 Answers 3

29

You are missing an else before 'O'. This works:

y = lambda symbol: 'X' if symbol==True else 'O' if symbol==False else ' '

However, I think you should stick to Adam Smith's approach. I find that easier to read.

answered Oct 30, 2015 at 15:26
Sign up to request clarification or add additional context in comments.

Comments

21

You can use an anonymous dict inside your anonymous function to test for this, using the default value of dict.get to symbolize your final "else"

y = lambda sym: {False: 'X', True: 'Y'}.get(sym, ' ')
answered Oct 30, 2015 at 15:27

2 Comments

Thank you, this is very helpful. I ticked w0lf's answer, because it exactly answered my question, but your approach is definitely more pythonic and logical.
@PM2Ring Whoops, right, because you're testing for equivalence to the value True and the value False, rather than testing for Truthyness or Falsyness. I'll edit
1

This is one way where you can try multiple if else in lambda function

Example,

largest_num = lambda a,b,c : a if a>b and a>c else b if b>a and b>c else c if c>a and c>b else a

largest_num(3,8,14) will return 14

Nikolas
45k19 gold badges132 silver badges201 bronze badges
answered Aug 28, 2021 at 16:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.