1

Please help me to understand how this works. Output is 4

a=4
b=7

x=lambda: a if 1 else b
lambda x: 'big' if x > 100 else 'small'
print(x())
2
  • 2
    whats your question ? is it about if - else or about lambda expression ? Commented Jun 15, 2016 at 7:17
  • 1
    You should read about the lambda function. Commented Jun 15, 2016 at 7:18

3 Answers 3

5

First, let's remove this line as it doesn't do anything:

lambda x: 'big' if x > 100 else 'small'

This lambda expression is defined but never called. The fact that it's argument is also called x has nothing to do with the rest of the code.

Let's look at what remains:

a = 4
b = 7

x = lambda: a if 1 else b

print(x())

Here x becomes a function as it contains code. The lambda form can only contain expressions, not statements, so it has to use the expression form of if which is backward looking:

true-result if condition else false-result

In this case the condition is 1, which is always true, so the result of the function x() is always the value of a, assigned to 4 earlier in the code. Effectively, x() acts like:

def x():
    return a

Understanding the differences between expressions and statements is key to understanding code like this.

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

Comments

0

Your x is always equals to 4, as it takes no arguments and if 1 is always True. Then you have lambda expression that's not assigned to any variable, neither used elsewhere. Eventualy, you print out x, which is always 4 as I said above.

P.S. I strongly suggest you to read Using lambda Functions from Dive into Python

Comments

0

Let me translate that for you.

You assign to x a lambda function with no arguments. Because 1 always evaluates as true, you always return the externally defined variable a, which evaluates as 4. Then, you create a lambda function with one argument x, which you don't assign to a variable/access name, so it is lost forever. Then, you call function x, which always returns a. Output is 4.

Comments

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.