SoFunction
Updated on 2024-11-18

How Python Defines Anonymous or Inline Functions

concern

You want to create a very short callback function for the sort() operation, but instead of writing a one-line function in def, you want to create it inline via some shortcut.

prescription

When some functions are simple and just compute the value of an expression, you can use lambda expressions instead. For example:

>>> add = lambda x, y: x + y
>>> add(2,3)
5
>>> add('hello', 'world')
'helloworld'
>>>

The lambda expression used here has the same effect as below:

>>> def add(x, y):
...   return x + y
...
>>> add(2,3)
5
>>>

Typical usage scenarios for lambda expressions are things like sorting or data reduce:

>>> names = ['David Beazley', 'Brian Jones',
...     'Raymond Hettinger', 'Ned Batchelder']
>>> sorted(names, key=lambda name: ()[-1].lower())
['Ned Batchelder', 'David Beazley', 'Raymond Hettinger', 'Brian Jones']
>>>

talk over

Although lambda expressions allow you to define simple functions, there are limits to their use. You can only specify a single expression whose value is the final return value. That means you can't include other language features, including multiple statements, conditional expressions, iteration, exception handling, and so on.

You can write most python code without using lambda expressions. However, when someone writes a lot of short functions that compute the value of an expression or a program that requires the user to supply a callback function, you'll see lambda expressions in action.

Above is Python how to define anonymous or inline function details, more information about Python define anonymous or inline function please pay attention to my other related articles!