SoFunction
Updated on 2025-03-04

Detailed explanation of the use of lambda expressions in Python (full transparent version)

1. Preface

lambdaExpressions are a concise and anonymous function expression in Python. They are used to create simple functions, usually used without the need to define a complete function.lambdaThe syntax of expressions is very concise and is suitable for writing small functions in one line.
Next, we start from specific examples and understand how to use lambda expressions from shallow to deeper.

2. Basic grammar

lambda parameter1, parameter2, ... : expression
  • lambdaThe boot keyword indicates that this is an anonymous function.
  • The parameters are immediately followed by, separated by commas.
  • The colon is followed by the function's expression, that is, the return value.

Equivalent to abbreviationdefFunction definition.

3. Give a simple example:

# Normal functionsdef add(x, y):
    return x + y

# Write it with lambda expressionadd_lambda = lambda x, y: x + y

# Callprint(add(2, 3))         # Output: 5print(add_lambda(2, 3))  # Output: 5

In this example,add_lambdaIt is equivalent toaddanonymous function, but it useslambdaExpressions are defined.

4. Common application scenarios

1. Used to sort functions

When we need to sort a list of complex data types such as tuples, dictionaries, etc., we usually uselambdato define the rules for sorting.

For example, in the parameters of the .sort sort function in the list, use key= a lambda expression to specify the sorting rules.

# Sort by the second element in the tuplepoints = [(1, 2), (3, 1), (5, 4)]
(key=lambda x: x[1])
print(points)  # Output: [(3, 1), (1, 2), (5, 4)]

In the example of the sort function, we usedlambdaExpressions and listssortMethod, sort a list containing tuples. Next, I will explain the working principle of this example step by step.

sort() method introduction

sort()is a built-in method for lists in Python, used forOn-siteSort the list (that is, the original list will be modified directly). It can sort list elements according to the default order (i.e., numbers from small to large and strings in dictionary order).

We can usekeyParameters customize the sorting rules.keyAccepts a function that generates the value used for comparison.

For example, by default,sort()The method is based on the value sorting of elements:

numbers = [3, 1, 2]
()
print(numbers)  # Output: [1, 2, 3]

However, if we want to sort by custom rules, such as sorting by some element of a tuple (such as a second element), we can usekeyParameters.

The function of lambda expression

In this example, we want to use a list of multiple tuplespointsSort, and the ordering is based on the second element of each tuple (the element with index 1). To implement this function, we uselambdaExpression:

key=lambda x: x[1]

herexis each tuple in the list,x[1]Represents the second element of the tuple. We tellsortMethods should be sorted according to the second element of each tuple.

Detailed explanation

  • Data structurepoints = [(1, 2), (3, 1), (5, 4)]This is a list of three tuples, each containing two numbers. For example,(1, 2)Denotes the coordinates of a point,1yesxCoordinates,2yesyCoordinates.

  • lambdaExpression:key=lambda x: x[1]

    • xRepresents each tuple in the list.
    • x[1]Extract the second element of the tuple.
    • lambdaThe function of expressions is to tellsortMethod, you only need to consider the second element of each tuple for comparison sorting.
  • Sorting process

    • sort()The method starts with the first tuple in the list and calls each tuplelambda x: x[1], return the value of the second element as the basis for sorting.

    • Pair tuple(1, 2)lambdareturn2. Pair tuple(3, 1),return1. Pair tuple(5, 4),return4

    • Then,sort()Method according to124The order of  sorts, and the result is:[(3, 1), (1, 2), (5, 4)]

  • Final result
    Sort listpointsfor[(3, 1), (1, 2), (5, 4)]. This result is sorted from small to large according to the second element of each tuple.

Further expansion

If we want to tupleThe first elementSorting, just need tox[1]Change tox[0]

(key=lambda x: x[0])
print(points)  # Output: [(1, 2), (3, 1), (5, 4)]

If you want to achievedescending orderSort, you can setreverse=True

(key=lambda x: x[1], reverse=True)
print(points)  # Output: [(5, 4), (1, 2), (3, 1)]

Summarize

lambdaExpressions are used in sorting functions to concisely define the basis for sorting. By passingkeyParameters, we can easily customize the sorting rules, such as sorting by a specific element in a tuple.

2. Combined with map, filter, reduce and other functions

lambdaExpressions andmapfilterreduceThe use of contour higher-order functions is a powerful tool in Python programming. Next, we will explain these three functions in detail and their combination.lambdaUsage of  .

1. Map() function

map()Functions are used to apply a function to each element in the iterable object and return a new iterator. It can accept a function and one or more iterable objects (such as lists, tuples).

grammar:

map(function, iterable)
  • functionis a function to be applied to each element.
  • iterableis an iterable object (such as lists, tuples, etc.).

When combinedlambdaWhen used,lambdaExpressions are passed as an anonymous function tomap()

Example: Square each number in the list

nums = [1, 2, 3, 4, 5]

# Use lambda expressions and mapssquared = map(lambda x: x**2, nums)

# Convert the results to a list and print itprint(list(squared))  # Output: [1, 4, 9, 16, 25]

explain:

  • lambda x: x**2is an anonymous function used to calculate the square of each number.
  • map()The functions willlambdaApplied tonumsEach element in the list, i.e.12345, and then return the result after each element is squared.

Common function writing equivalent:

def square(x):
    return x ** 2

squared = map(square, nums)
print(list(squared))  # Output: [1, 4, 9, 16, 25]

2. filter() function

filter()Functions are used to filter elements in an iterable object, keeping those that make the function returnTrueelements. It also returns an iterator.

grammar:

filter(function, iterable)
  • functionis a function used to test each element, returningTrueorFalse
  • iterableIt is an iterable object that needs to be filtered.

WhenlambdaWhen using expressions in combination,lambdaCan be used as a filter condition.

Example: Filter out even numbers in the list

nums = [1, 2, 3, 4, 5]

# Use lambda expressions and filtersevens = filter(lambda x: x % 2 == 0, nums)

# Convert the results to a list and print itprint(list(evens))  # Output: [2, 4]

explain:

  • lambda x: x % 2 == 0is an anonymous function used to judgexWhether it is an even number.
  • filter()The functions willlambdaApplied tonumsEach element in the list, returnTrueThe element of   is retained, returnFalseThe elements of   are filtered out. Therefore, the end result is to retain even numbers2and4

Common function writing equivalent:

def is_even(x):
    return x % 2 == 0

evens = filter(is_even, nums)
print(list(evens))  # Output: [2, 4]

3. Reduce() function

reduce()Functions are used to accumulate elements in an iterable object and finally merge them into a value. It needs to be importedfunctoolsmodule, because it does not belong to Python's built-in functions.

grammar:

from functools import reduce
reduce(function, iterable)
  • functionis a function that requires two parameters to merge the previous calculation result with the next element.
  • iterableIt is an iterable object.

WhenlambdaWhen expressions are combined,lambdaRules used to define accumulation.

Example: Calculate the accumulated sum of all elements of the list

from functools import reduce

nums = [1, 2, 3, 4, 5]

# Use lambda expressions and reducetotal = reduce(lambda x, y: x + y, nums)

print(total)  # Output: 15

explain:

  • lambda x, y: x + yis an anonymous function that accepts two parametersxandy, and return their sum.
  • reduce()The function first takes the first two elements1and2Added to get3, and then3and3Added to get6, and so on until all elements are processed. Finally return the accumulated result15

Common function writing equivalent:

def add(x, y):
    return x + y

total = reduce(add, nums)
print(total)  # Output: 15

Summarize

  • map(): Apply a function to each element and return the transformation result of each element. Suitable for batch operation.
  • filter(): Filter elements according to conditions, retaining elements that meet the conditions.
  • reduce(): Performs accumulation operations on elements in the sequence, suitable for scenarios where you need to be reduced to a single value.

lambdaExpressions can be conveniently combined with these higher-order functions, reducing code redundancy and explicit definition of functions.

3. Functions used for internal or single-use functions

When the function only needs to be used once, you can use it directlylambdaExpression without defining new function names.

def apply_operation(x, operation):
    return operation(x)

# Pass anonymous functions using lambdaresult = apply_operation(5, lambda x: x * 2)
print(result)  # Output: 10

5. Summary

lambdaExpressions are used to simplify code, especially for short functions, avoid explicitly defining complete functions. Although it is convenient, when the functions are more complex, it is still recommended to use ordinary function definitions to improve the readability of the code.

This is the end of this article about the detailed explanation of the use of lambda expressions in Python. For more related contents of lambda expressions in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!