SoFunction
Updated on 2024-11-16

Detailed usage of lambda expressions in python

This article example describes the lambda expression usage in python. Shared for your reference, as follows:

Here's an introduction to lambda functions for you.

A lambda function is a quick way to define a one-line minimal function, borrowed from Lisp, that can be used anywhere a function is needed. The following example compares the traditional way of defining a function with the lambda way of defining a function:

>>> def f ( x ,y):
...   return x * y
...
>>> f ( 2,3 )
6
>>> g = lambda x ,y: x * y
>>> g ( 2,3 )
6

As you can see, the two functions get the same result, and for the realization of simple functions, the use of lambda function to define a more streamlined and flexible, you can also directly assign the function to a variable, using the variable name to indicate the function name.

Actually, lambda functions don't need to be assigned to a variable in many cases.

There are a few more caveats to using lambda functions: A lambda function can take any number of arguments (including optional arguments) and return the value of a single expression. A lambda function cannot contain commands and cannot contain more than one expression.

The following is a simple demonstration of how to implement custom sorting using the lambda function.

class People :
  age = 0
  gender = 'male'
  def __init__ ( self , age , gender ):
    self . age = age
    self . gender = gender
  def toString ( self ):
    return 'Age:' + str ( self . age ) + ' /t Gender:' + self . gender
List = [ People ( 21 , 'male' ), People ( 20 , 'famale' ), People ( 34 , 'male' ), People ( 19 , 'famale' )]
print 'Befor sort:'
for p in List :
  print p . toString ()
List . sort ( lambda p1 , p2 : cmp ( p1 . age , p2 . age ))
print ' /n After ascending sort:'
for p in List :
  print p . toString ()
List . sort ( lambda p1 , p2 : - cmp ( p1 . age , p2 . age ))
print ' /n After descending sort:'
for p in List :
  print p . toString ()

The above code defines a People class and implements a lambda function to sort the list containing objects of the People class in ascending and descending order according to the age of the People. The result is as follows:

Befor sort:
Age:21    Gender:male
Age:20    Gender:famale
Age:34    Gender:male
Age:19    Gender:famale
After ascending sort:
Age:19    Gender:famale
Age:20    Gender:famale
Age:21    Gender:male
Age:34    Gender:male
After descending sort:
Age:34    Gender:male
Age:21    Gender:male
Age:20    Gender:famale
Age:19    Gender:famale

The lambda statement is used to create new function objects and return them at runtime.

Example: Using the lambda form

#!/usr/bin/python
# Filename: 
def
make_repeater(n):
  return lambda s: s*n
twice = make_repeater(2)
print twice('word')
print twice(5)

Output:

$ python 
wordword
10

How it works

Here, we have used the make_repeater function to create a new function object at runtime and return it.

The lambda statement is used to create a function object. Essentially, a lambda takes one argument, followed only by a single expression as the body of the function, and the value of the expression is returned by the newly created function. Note that even the print statement cannot be used in the lambda form; only expressions can be used.

Difference between def and lambda

The main difference between them is that python def is a statement and python lambda is an expression, and it's important to understand this so that you can understand them. Here's a look at their applications.
First of all, statements can be nested in python, so if you need to define a method based on a condition, you can only use def.

You'll get an error if you use lambda.

a = 2
if a > 1 :
  def info ():
    print 'haha'
else :
  def test ():
    print 'test'

And sometimes you need to operate in python expression, then you need to use expression nesting, this time python def can not get the result you want, it can only be used python lambda

An example is given below:

g = lambda x : x+2
info = [g(x) for x in range(10)]
print info

With the above examples, I hope you have a good understanding of the similarities and differences between python def and lambda. If you are interested in python functions, you can check out: python function return value , python function parameters

python lambda is the use of lambda to create anonymous functions in python, whereas methods created with def are named, so apart from the fact that the method names are different on the face of it, what else about python lambda is different from def?

① python lambda creates a function object but does not assign that function object to an identifier, whereas def assigns the function object to a variable.

② python lambda it is just an expression while def is a statement.

Here is the format of python lambda, it looks so streamlined.

lambda x: print x

If you use python lambda in python list parsing, I don't think it makes a lot of sense, because python lambda creates a function object, but then immediately discards it, because you're not using its return value, which is that function object. It's also because lambda is just an expression that it can be used directly as a member of a python list or a python dictionary, for example:

info = [lamba a: a**3, lambda b: b**3]

There is no way to use def statement directly instead in this place. Because def is a statement, not an expression, you can't nest expressions in it, and lambda expressions can only have one expression after the ":". That is to say, in def, what can be returned by return can also be put after lambda, and what cannot be returned by return cannot be defined after python lambda. Therefore, statements like if or for or print cannot be used in a lambda, which is generally only used to define simple functions.

Here are a few examples of python lambda's

① of a single parameter:

g = lambda x:x*2
print g(3)

The result is 6

② of multiple parameters:

m = lambda x,y,z: (x-y)*z
print m(3,1,2)

The result is 4

When you have nothing to write a program, use python lambda more often and you will become skilled.

Readers interested in more Python related content can check out this site's topic: theSummary of Python image manipulation techniques》、《Python Data Structures and Algorithms Tutorial》、《Python Socket Programming Tips Summary》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope that what I have said in this article will help you in Python programming.