Python. Lambda expressions. Anonymous functions. The lambda keyword




Lambda expressions. Anonymous functions. The lambda keyword. Transition table


Contents


Search other websites:

1. Anonymous functions. Concepts. The lambda keyword. General form

The Python language allows you to define function objects as expressions. In this case, the def keyword is replaced with the lambda keyword.

The difference between using def and lambda is that in the case of def, an expression associates a name with a function, and in the case of a lambda, an expression returns a function.

The general form of declaring a lambda expression is as follows:

lambda agrument1, agrument2, ..., argumentN: expression

here

  • argument1, argument2, argumentN – the names of the arguments that the lambda expression uses;
  • expression – the lambda expression itself.

After analyzing the general form of a lambda expression, you can come to the following conclusions:

  • lambda expression is written in a single line. If you try to put expression on another line, the compiler will throw an error;
  • lambda expressions create functions that don’t have a name. Such functions are called anonymous functions.

 

2. Use cases for lambda expressions

Once a lambda expression is declared, it can be used in the following cases:

  • as a function. This is the case when a lambda expression is assigned to some name. The lambda expression is then called with this name;
  • as an element (literal) of a tuple or list;
  • as an element (literal) of a dictionary that performs some action on demand. In this case, a so-called transition table is formed.

 

3. Differences between declaring and using lambda expressions (lambda) and functions (def)

There are the following differences between declaring and using lambda expressions and functions:

  • lambda expression is declared using the lambda keyword. The function is declared using the def keyword;
  • lambda expressions are expressions, def are statements. This means that a lambda expression can be used where def is not allowed: inside literals or function calls;
  • lambda expression contains only one expression that is returned. The result of evaluating an expression is the result of a lambda expression. You don’t need to use the return statement to return a result from a lambda expression;
  • unlike function declarations (def), lambda expressions are designed to evaluate simpler pieces of code than functions;
  • the program code of the lambda expression is formed as a single line. The program code of a function can contain a large number of lines.

 

4. The advantages of using lambda expressions

Using lambda expressions provides the following advantages:

  • lambda expressions are useful for creating small functions;
  • lambda expressions simplify program code in which you need to embed small fragments;
  • program code can conveniently use a lambda expression instead of defining functions where necessary;
  • lambda expressions provide a so-called code proximity. Anonymous instructions are placed side by side in the program, which increases its readability and perception, and does not require the use of additional names (as is the case with functions). Reducing the number of names in the program reduces possible conflicts of these names with other names in the module file.

 

5. Examples showing the most basic lambda expressions. Differences between def and lambda statements. Calling lambda expressions as names

The following examples demonstrate:

  • declaration of a lambda expression and its assignment to some name;
  • calling (using) a lambda expression by name;
  • differences between declaring and using functions (def) and lambda expressions (lambda).

Example 1. Calculation of the product of three numbers.

# Lambda expressions and functions

# Calculation of the product of numbers.
# Lambda expression that returns the product of three numbers
multL = lambda a, b, c: a * b * c # lambda expression on one line
resLambda = multL(2,5,5)         # call the lambda expression

# Function that returns the product of three numbers
def multF(a, b, c):
    return a*b*c

resFunc = multF(2,5,5) # function call

# Display the result
print("resLambda = ", resLambda)
print("resFunc = ", resFunc)

The result of the program

resLambda = 50
resFunc = 50

In the above example, the result of the lambda expression is assigned the name multL

multL = lambda a, b, c: a * b * c

Then calling the lambda expression with specific values (a = 2, b = 5, c = 5) is assigned the name (object) resLambda

resLambda = multL(2,5,5) # call the lambda-expression

As a result, the resLambda object contains the product of numbers 2 * 5 * 5 = 50.

Example 2. A lambda expression that returns the modulus of a complex number.

# Lambda expressions and functions
import math

# 1. Lambda expression that defines the modulus of a complex number
absL = lambda a, b: math.sqrt(a*a + b*b) # declaration
resLambda = absL(3, 4) # calling

# 2. Function that returns the modulus of a complex number
#   Function declaration
def absF(a, b):
    return math.sqrt(a*a + b*b)

resFunc = absF(3,4) # function call

# Display the result
print("resLambda = ", resLambda)
print("resFunc = ", resFunc)

The result of the program

resLambda = 5.0
resFunc = 5.0

Example 3. Lambda expression that determines the discriminant of a quadratic equation by the coefficients a, b, c.

# Lambda-expressions and functions

# 1. Lambda expression that calculates the discriminant based on the coefficients a, b, c
discrL = lambda a, b, c: b*b - 4*a*c
print("discrLambda = ", discrL(3,4,5))

# 2. A function that returns the discriminant based on the coefficients a, b, c
# Declaring a function
def discrF(a, b, c):
    return b*b-4*a*c

print("discrFunc = ", discrF(3,4,5))

The result of the program

discrLambda = -44
discrFunc = -44

 

6. Examples of using lambda expressions as list literals

Example 1. Using a lambda expression as a list literal.

Based on lambda expressions, generate a list of random numbers from 0 to 1.

# Lambda expressions as list literals
import random

# A dictionary in which three random numbers are formed
# using a lambda expression
L = [ lambda : random.random(),
    lambda : random.random(),
    lambda : random.random() ]

# Display the result
for l in L:
    print(l())

The result of the program

0.5129490134837236
0.8638007610222296
0.915211196027481

Example 2. A tuple is formed in which the elements are multiplied by different numbers. Demonstrated using a tuple for a string.

 # Lambda expressions as tuple literals

import random

# A tuple in which three string literals are formed
# using a lambda expression
T = ( lambda x: x*2,
    lambda x: x*3,
    lambda x: x*4 )

# Print the result for the string 'abc'
for t in T:
    print(t('abc'))

The result of the program

abcabc
abcabcabc
abcabcabcabc

 

7. Examples of using lambda expressions to form transition tables in dictionaries

Example 1. Using lambda expressions to form transition tables.

Create a transition table (dictionary), in which its name is displayed by the number of the day of the week. Demonstrate the work of the created table.

# lambda-expressions and transition tables

# Dictionary, which is a transition table
Dict = {
    1 : (lambda: print('Monday')),
    2 : (lambda: print('Tuesday')),
    3 : (lambda: print('Wednesday')),
    4 : (lambda: print('Thursday')),
    5 : (lambda: print('Friday')),
    6 : (lambda: print('Saturday')),
    7 : (lambda: print('Sunday'))
    }

# Call a lambda expression that outputs the name of Tuesday
Dict[2]() # Tuesday

Example 2. A transition table (dictionary) Area is formed, in which the area of known figures is calculated.

# Lambda expressions and transition tables

import math

# A dictionary that is a transition table in which, under the name
# of the figure, its area is displayed
Area = {
    'Circle' : (lambda r: math.pi*r*r), # circle
    'Rectangle' : (lambda a, b: a*b),   # rectangle
    'Trapezoid' : (lambda a, b, h: (a+b)*h/2.0) # trapezoid
    }

# Call a lambda expression that outputs the area of a circle of radius 2
print('Area of circle = ', Area['Circle'](2))

# Print the area of a rectangle that has a size of 10*13
print('Area of rectangle = ', Area['Rectangle'](10, 13))

# Output the area of a trapezoid for a=7, b=5, h=3
areaTrap = Area['Trapezoid'](7, 5, 3)
print('Area of trapezoid = ', areaTrap)

The result of the program

Area of circle = 12.566370614359172
Area of rectangle = 130
Area of trapezoid = 18.0

 

8. Is it possible to use standard control statements if, for, while in lambda expressions?

The answer is no.

According to the syntax, the lambda expression is placed on one line. If you try to put a while statement in the body of a lambda expression on one line, the Python interpreter will throw an “Invalid syntax” error as shown below

# Error: "Invalid syntax"
lmbd = lambda n: while n>0: n=n-1
print("lmbd = ", lmbd)

The same goes for other control structures.

 


Related topics