A lambda expression is an anonymous function, a function that does not have a function name. A lambda expression can represent closures (notice differs from the traditional mathematical sense).
1. Lambda expression in Python
A lambda expression is a special type of defined function in Python that allows you to define an anonymous function. Unlike other languages, the function body of a Python lambda expression can have only one statement, which is the return value expression statement. Its syntax is as follows:
Lambda parameter list: function return value expression statement The following is an example of a lambda expression:
1234 |
#!/usr/bin/envpython
li
=
[{
"age"
:
20
,
"name"
:
"def"
},{
"age"
:
25
,
"name"
:
"abc"
},{
"age"
:
10
,
"name"
:
"ghi"
}]
li
=
sorted
(li,key
=
lambda
x:x[
"age"
])
print
(li)
|
If you don't use a lambda expression and write a regular function, you need to do this:
123456 |
#!/usr/bin/envpython
def
comp(x):
return
x[
"age"
]
li
=
[{
"age"
:
20
,
"name"
:
"def"
},{
"age"
:
25
,
"name"
:
"abc"
},{
"age"
:
10
,
"name"
:
"ghi"
}]
li
=
sorted
(li,key
=
comp)
print
(li)
|
2. There are lambda expressions in C #, Java, C + +
Lambda expression of Python learning