Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python lambda raises variable not defined error with multiple arguments

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?

like image 886
Stray Avatar asked Dec 11 '22 15:12

Stray


1 Answers

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.

like image 192
BrenBarn Avatar answered May 12 '23 16:05

BrenBarn