1

I came across a Python Challenge question with a variable declaration I didn't understand. It was asking for the output of this code.

a = "abcd"
b = "abc"
func = (lambda s:s[1:]) or (lambda s:s[:-1])
print(func(b))

I pretty much ignored the second lambda and got the correct answer which was:

"bc"

My questions are, what is the practical use of having an "or" during variable assignment between lambda functions? And how would I access the second lambda in an "or" statement? What would be an example of the second lambda function being invoked?

Note: My question has been marked as a duplicate. The other question and answer provided great information and supplementary knowledge related to my topic. However, that question was dealing with return values and general statements. I think my question is different in that it deals with variable assignment rather than return values, and the application of "or" to functions, which I don't see covered in the other question. I would still like clarification on the concept of truthiness or falsey values applied to a lambda function.

dPad
  • 11
  • 2

1 Answers1

1

Let's look at this:

a = None or 1 
b = 'ABC' or None
c = None or True
d = 'F' or 'Z'
e = 1 or 2
f = None or None or 5
g = False or None or True
h = 1==2 or 'T'

Run the output for each variable and you can see that the variables get assigned with the first value as long as it is not False/None.

dfundako
  • 8,022
  • 3
  • 18
  • 34
  • This makes a lot of sense, I appreciate it! So in the specific case above, the second lambda will never be invoked. Lambda's wouldn't exactly be the best example for the usage of "or" I assume. – dPad Jun 20 '18 at 18:44