[Python][For noobs] What is anonymous/lambda function?

These functions are JUST SHORT ONE-LINE functions to be used as an argument for other functions, like sorting (sorted()). Shorter than ~40 symbols.

More advanced Python developers/programmers use them in map() and filter() functions.

AS SIMPLE AS THAT. Most of the time, these are just short functions you don't want to define as a 'usual' functions. Often, used only once, so you won't separate them.

Why anonymous? Because they have no name.

Why lambda? This term inherited from Lisp, forget about it for a moment. (Lambda functions are also inherited from Lisp.)

Actually, in Python you can define function via lambda. For example, square root:

>>> lambda x: x**2
<function <lambda> at 0x7f356a3fe200>

>>> f=lambda x: x**2

>>> f(2)
4

>>> f(10)
100

I'm not a Lisp/Scheme expert, but as far as I know, in toy Lisp interpreters, function definition is actually a syntactic sugar for assigning anonymous lambda function to a function's name. Of course, you can define 'usual' functions via lambda there.

(the post first published at 20230313.)


List of my other blog posts.

Subscribe to my news feed

Yes, I know about these lousy Disqus ads. Please use adblocker. I would consider to subscribe to 'pro' version of Disqus if the signal/noise ratio in comments would be good enough.