1

I'm checking this function which should either loop forward or backward in an array depending on the parameters passed to it. To update the index, the code has something like this:

>>> def updater(me, x, y):
...     fun = lambda x : x + 1 if x < y else lambda x : x - 1
...     return fun(me)
... 
>>> updater(2, 1, 0)
<function <lambda> at 0x7ff772a627c0>

I realize that the above example can be easily corrected if I just use a simple if-return-else-return sequence but this is just a simplification, and in the actual code it's more than just checking two integers. And yes, there is a one-liner conditional involved which returns a function (don't ask, not my own code).

Sanity-checking my interpreter...

>>> updater = lambda x: x + 1
>>> updater(2)
3

So why does the first example return an function?

1 Answer 1

2

These parentheses should help you see how your code is being interpreted:

fun = (lambda x : (x + 1 if x < y else (lambda x : x - 1)))

So to solve your problem, just add some more parentheses:

fun = (lambda x: x + 1) if x < y else (lambda x: x - 1)

Or use only one lambda:

fun = lambda x: x + (1 if x < y else -1)
Sign up to request clarification or add additional context in comments.

1 Comment

Ohhhhhh...wow. Never forget the old maxim from Programming 101 then: When in doubt use parentheses!

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.