Join us
@coucou_camille ・ Jun 17,2022 ・ 2 min read ・ 1k views
A lambda function is a anonymous function with syntax lambda args: expression . The expression is executed on the arguments and the result is returned.
A lambda function is a anonymous function with syntax lambda args: expression
. The expression is executed on the arguments and the result is returned. Each lambda function consists of 3 parts:
A simple example: square = lambda x: x**2
is equivalent to the standard Python function definition as follows:
Use cases like square(4)
will give the same results in both cases.
Example for getting the sum of squares of 2 variables:
As can be seen in the previous examples, a lambda function has the following characteristics:
def
keyword.filter
, map
, sort
and reduce
.Filter function takes on the form filter(function, iterable)
. It is used to filter elements satisfying certain conditions from an iterable object such as lists and sets. The function
argument is often implemented using a lambda function:
Map function takes on similar format as filter
and is used to perform a uniform operation for all elements in a sequence:
Syntax: reduce(function, sequence)
The reduce
function, like map
, is also used to perform an operation function
on each element in the sequence
. However it works a bit differently in that the operation is performed among the elements, rather than performed on each element separately.
For example, map
is used if you wish to double each element, but reduce
is used if you want to get the sum of all elements in the sequence.
For example, if we have a list of price and volume retrieved from order book as follows: orders = [[1.21, 34600], [1.22, 56490], [1.25, 3970], [1.28, 127500], [1.3, 87900]]
, each element in list represents a price-volume pair. To sort the list, we could employ lambda functions to specify the key used for sorting.
orders = [[1.21, 34600], [1.22, 56490], [1.25, 3970], [1.28, 127500], [1.3, 87900]]# sort by price
sorted(orders, key=lambda x: x[0])>>> [[1.21, 34600], [1.22, 56490], [1.25, 3970], [1.28, 127500], [1.3, 87900]]
# sort by volume
sorted(orders, key=lambda x: x[1])>>> [[1.25, 3970], [1.21, 34600], [1.22, 56490], [1.3, 87900], [1.28, 127500]]
Internally, both lambda
and def
functions work exactly the same. The dis
keyword exposes a readable version of Python bytecode allowing inspection of instructions. Evaluating both versions of square
functions defined in beginning of this article:
The processes undertaken by both functions are observed to be exactly the same. So there is no real difference in the way they execute.
Join other developers and claim your FAUN account now!
Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.