0

I was looking but I don't understand in a practical way the difference between an anonymus function and a normal function.

Anonymuos function in python(lambda):

triangle_area = lambda base, height: (base, height) / 2

Normal function:

def triangle_area(base, height):
     return (base, height) / 2

But when I call the function for me is the same, regardless of the way you created the function.

triangle_area(10,7)

I hope I explained myself well.

Thanks for your help.

  • Anonymous functions are mostly there to save space. If you are using it one time, or if it is extremely simple, then it is better to make it in one line and be done with it. – Saddy Jan 07 '20 at 22:33
  • anonymous functions should virtually always remain anonymous, e.g. a key function `sorted(lst, key = lambda x: len(x)**2` or a list of functions `[lambda x: x, lambda x: x /2]` etc.-- there are some other differences, you can do everything in a lambda expression you can do in a regular `def` function of course – Chris_Rands Jan 07 '20 at 22:35

1 Answers1

0

You would ideally never write it the first way; "named lambdas" are actually against the recommendations of PEP8:

Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

Yes:

def f(x): return 2*x

No:

f = lambda x: 2*x

Lambdas are useful however when you don't need to give the function a name:

map(lambda n: n * 2, [1, 2, 3])

This is essentially the same as:

def double(n):
    return n * 2

map(double, [1, 2, 3])

But the former is more succinct.

Community
  • 1
  • 1
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117