Python Tutorial - Lambda Expression

For defining a simple function, Python also provides another method, which is to use the lambda expression described in this section.

Lambda expressions, also known as anonymous functions, are often used to represent functions that contain only one line of expression. If the body of a function has only one line of expression, the function can be replaced with a lambda expression.

The syntax of a lambda expression is as follows:

name = lambda [list]: expression

Among them, to define a lambda expression, you must use:

  • lambda keyword;
  • [list] as an optional parameter is equivalent to defining the function to be a specified parameter list;
  • value is the name of the expression.

The syntax format is converted to the form of ordinary functions, as follows:

def name (list):
   return expression
name (list)

Obviously, using a normal method to define this function requires 3 lines of code, while using a lambda expression requires only 1 line.

For example, if you design a function that sums 2 numbers, use the ordinary function, which is defined as follows:

def add (x, y):
    return x + y
print (add (3,4))

The output is:


Since there is only 1 line of expression inside the add function in the above program, this function can be directly expressed by a lambda expression:

add = lambda x, y: x + y
print (add (3,4))

The output is:


A lambda expression can be understood as a shorthand version of a simple function (the body of which is a single-line expression). Lambda expressions have two advantages over functions:

  • For single-line functions, using lambda expressions can save the process of defining functions and make the code more concise;
  • For functions that do not require multiple reuse, lambda expressions can be released immediately after they are used up, improving the performance of program execution.

Python Eval and Exec Functions

The eval and exec functions are both built-in functions of Python. Since these two functions are similar in function and usage, they are introduced in this section.

The functions of the eval and exec functions are similar, and both can execute Python code as a string (the code is provided as a string), which is equivalent to a Python interpreter. The difference between the two is that eval returns results after execution, while exec returns no results (detailed examples will be given later in the article).

Python Eval and Exec Usage

The syntax of the eval function is:

eval (source, globals = None, locals = None, /) /p>

The syntax of the exec () function is as follows:

exec (source, globals = None, locals = None, /)

It can be seen that the syntax format of the two is the same except for the function name. The specific meaning of each parameter is as follows:

  • expression: This parameter is a string representing the statement to be executed. This statement is restricted by the last two dictionary type parameters globals and locals. Only functions and variables in the scope of the globals dictionary and locals dictionary can be executed.
  • globals: This parameter controls a global namespace, that is, expression can use functions in the global namespace. If the globals parameter is provided without a custom __builtins__, the system will copy the __builtins__ in the current environment to the globals provided by itself, and then calculate it; if the globals parameter is not provided, Use Python's global namespace.
  • locals: This parameter controls a local namespace, similar to globals. When it overlaps or conflicts with globals, locals will prevail. If locals is not provided, it defaults to globals.

Note that __builtins__ is a Python built-in module. The int, str, and abs that are usually used are in this module. The print (dic ["__ builtins__"]) statement lets you see the value of __builtins__.

First, use the following example to demonstrate the effect of the parameter globals scope, and notice when it copies __builtins__ to the globals dictionary:

dic = {} #define a word
dic ['b'] = 3 #Add an element to dic with key b
print (dic.keys ()) #Print the key of dic first, there is an element b
exec ("a = 4", dic) #The statement executed by exec is followed by a scope dic
print (dic.keys ()) #exec, dic has one more key

The output is:

dict_keys(['b', '__builtins__', 'a'])

The following code executes a = 4 code under the scope dic. It can be seen that the key in dic before exec () has only one b. After executing exec (), the system generates two new keys in dic, a and __builtins__. Among them, a is the variable generated by the execution statement, and the system places it in the specified scope dictionary; __builtins__ is a built-in key added by the system.

The usage of the locals parameter is very simple, for example:

a = 10
b = 20
c = 30
g = {'a': 6, 'b': 8} #define a dictionary
t = {'b': 100, 'c': 10} #define a dictionary
print (eval ('a + b + c', g, t)) #define a dictionary 116

The output is:


The Difference Between Exec () and Eval () in Python

As mentioned earlier, the difference is that eval () returns a result after execution, while exec() does not return a result after execution. for example:

a = 1
exec ("a = 2") #Equivalent to directly executing a = 2
print (a)
a = exec ("2 + 3") #Equivalent to executing 2 + 3 directly, but there is no return value, a should be None
print (a)
a = eval ('2 + 3') #Execute 2 + 3 and return the result to a
print (a)

The output is:



More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises