4

When trying to write a one line Fibonacci sequence that I understand, I'm having an issue with fib = lambda a, b: b, a + b as "'b' is not defined"

However, when I do sum = a, b, c: a + b + c I get no errors. sum(1, 2, 3) runs perfectly and returns 6.

I've researched global variables and found that if I set a and b to Null before starting, it doesn't give me an error, but is there a way not to do this?

1 Answer 1

14

You need to put parentheses around the lambda body:

fib = lambda a, b: (b, a + b)

Otherwise Python thinks it is this:

fib = (lambda a, b: b), a + b

Incidentally, there's no real purpose in using lambda if you're just going to assign the function to a name.

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

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.