1

Can someone please explain to me

  1. Why a is a list of True/False, while b is a list of lambdas?

  2. Why does the rule does not apply to c and d?

Codes:

foo = (lambda a, b: a >= b) if False else (lambda a, b: a <= b)
a = [foo(x, x+1) for x in xrange(10)]

foo = lambda a, b: a >= b if False else lambda a, b: a <= b
b = [foo(x, x+1) for x in xrange(10)]

bar = (lambda a, b: a*b*10) if False else (lambda a, b: a*b*100)
c = [bar(x, x+1) for x in xrange(10)]

bar = lambda a, b: a*b*10 if False else lambda a, b: a*b*100
d = [bar(x, x+1) for x in xrange(10)]

Thank you in advance.

4
  • In this expression, foo = lambda a, b: a >= b if descending else lambda a, b: a <= b there is no delimeter indicating the end of the lambda, so the if-else is inside the lambda. If descending is false, the else runs, and the outer lambda returns lambda a, b: a <= b. Commented Aug 13, 2014 at 21:16
  • Made a mistake, all keywords descending has been replaced with True. Thanks @BlackBear, @Joran Beasley Commented Aug 13, 2014 at 21:17
  • (b) is no longer a list of lambdas if you replace it with True Commented Aug 13, 2014 at 21:20
  • Thank you guys, now I understand why. As a question, I now changed all True to False for other people's benefits. Commented Aug 13, 2014 at 21:23

2 Answers 2

4

It is just a matter of operator precedence. Let's put some brackets to show how the statements are parsed:

(a) foo = (lambda a, b: a >= b) if True else (lambda a, b: a <= b)
(b) foo = lambda a, b: (a >= b if descending else lambda a, b: a <= b)

When evaluating (b) descending happens to be false, so all the elements become lambda a, b: a <= b

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

Comments

1
foo = lambda a, b: a >= b if descending else lambda a, b: a <= b
b = [foo(x, x+1) for x in xrange(10)]

can be rewritten as

foo = lambda a, b:  (a >= b if descending else lambda a, b: a <= b)
b = [foo(x, x+1) for x in xrange(10)]

which if it is descending is fine as LHS is evaluated to

foo = lambda a,b: a >= b  #does what you would expet

but if its not you get

foo = lambda a,b: lambda a,b:a<=b

which clearly returns a lambda not a value

you could change it to

foo = lambda a, b: a >= b if descending else  a <= b
b = [foo(x, x+1) for x in xrange(10)]

and it should work as you expect

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.