-4

What are the possible niuances (differences) between a method and a lambda? I have an identity function and wonder does it make much of a difference how I define it?

def ident(x): return x
ident = lambda x: x

These are surely functionally the same, but do they differ in performance or otherwise?

0xc0de
  • 8,028
  • 5
  • 49
  • 75
ArekBulski
  • 4,520
  • 4
  • 39
  • 61
  • 5
    Neither of those is a method. – juanpa.arrivillaga Sep 29 '17 at 02:14
  • You mean its a function? That is just words picking, honestly. – ArekBulski Sep 29 '17 at 02:17
  • 5
    Using precise vocabulary is important to understand the inner workings; don't dismiss it. – Reblochon Masque Sep 29 '17 at 02:18
  • No, it's *isn't just word picking*. That is a *crucial, functional difference in Python*. Note, you've tagged this with staticmethod, but that is just plain wrong. – juanpa.arrivillaga Sep 29 '17 at 02:20
  • But, to get to your question, performance differences are negligible, but more importantly, `lambda` functions only support expressions, where's `def` statements can have any combination of complex statements in their body. The *only* purpose of lambda is for convenience, usually as an argument to a higher order function, and if you assign lambda functions to a name, that negates their only use case. Indeed, although it is allowed, it is explicitly recommended against by PEP8 style guidelines. – juanpa.arrivillaga Sep 29 '17 at 02:31

1 Answers1

0

Both do the same, but neither is a method; the first is a function, the second, an anonymous function that you named by assigning it to a variable.

from the comments:

performance differences are negligible, but more importantly, lambda functions only support expressions, where's def statements can have any combination of complex statements in their body. The only purpose of lambda is for convenience, usually as an argument to a higher order function, and if you assign lambda functions to a name, that negates their only use case. Indeed, although it is allowed, it is explicitly recommended against by PEP8 style guidelines.
~ juanpa.arrivillaga

Community
  • 1
  • 1
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80