-1

Currently I am learning lambda functions in Python 3. Till now all I know about lambda functions is that its an anonymous function which can take any number of arguments but can contain only one expression.

So my question is that why do we need lambda functions if we can do the same using normal expression. I mean what was the actual purpose of introducing lambda functions?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • https://stackoverflow.com/questions/16501/what-is-a-lambda-function?rq=1 – oakca Mar 22 '19 at 13:47
  • 1
    There's no such thing as a lambda function. A lambda *expression* is one way to create a `function` object. – chepner Mar 22 '19 at 13:52
  • Python 3 almost didn't have lambda expressions. Things like `operator.itemgetter` were intended as replacements for the major use cases, and as you've noticed, there's nothing you can define with a lambda expression that you can't define with a `def` statement as well. In the end, they were retained, though. – chepner Mar 22 '19 at 13:57

2 Answers2

1

Occassionally you need a very simple function for a one-time use, e.g. to pass as a paramater to .sort() to tell it how to do the sorting. E.g. if you want to sort a list of tuples on their second element,

list_of_tuples.sort(key=lambda t: t[1])

is nicely concise, compared to

def first_element(t):
    return t[1]

list_of_tuples(key=first_element)

And that is all.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
0

i rarely use random functions, but i dislike to introduce a named function just to use as the key in sort. i prefer

lst = (('s', 5), ('b', 2), ('h', 3))
srt = sorted(lst, key=lambda x: x[1])

to

def sort_by(x):
    return x[1]

srt = sorted(lst, key=sort_by)
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111