The Python Oracle

Multiple if statements in a lambda function

This video explains
Multiple if statements in a lambda function

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop

--

Chapters
00:00 Question
00:45 Accepted answer (Score 27)
01:04 Answer 2 (Score 21)
01:26 Answer 3 (Score 1)
01:49 Thank you

--

Full question
https://stackoverflow.com/questions/3343...

Accepted answer links:
[This]: http://ideone.com/wjeDnd
[Adam Smith's approach]: https://stackoverflow.com/a/33439510/390...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #lambda

#avk47



ACCEPTED ANSWER

Score 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.




ANSWER 2

Score 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, ' ')



ANSWER 3

Score 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