Lambda Expressions in Python: Tutorial with Exampl

In Python, a lambda expression (or lambda function) is a way to create small, one-time, anonymous function objects. They are often used for small, one-time operations where a full function definition would be overly verbose.

Table of Contents

The syntax for a lambda expression is:

lambda arguments: expression

Here, arguments is a comma-separated list of arguments, and expression is a single Python expression that is returned by the lambda.

Code Examples

1. Basic Lambda Function

A simple lambda that takes an argument and multiplies it by 2:

f = lambda x: x * 2
print(f(7))  # Outputs: 14

2. Multiple Arguments

A lambda that takes two arguments and adds them:

add = lambda x, y: x + y
print(add(5, 3))  # Outputs: 8

3. Conditionals

Using a lambda with a conditional expression:

check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(4))  # Outputs: Even

4. Using Lambdas with map()

Applying a lambda to each element of a list:

numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x**2, numbers)
print(list(squares))  # Outputs: [1, 4, 9, 16, 25]

5. Using Lambdas with filter()

Filtering a list with a lambda:

numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # Outputs: [2, 4, 6]

6. Sorting with Lambda

Sorting a list of tuples by the second element:

pairs = [(1, 2), (3, 1), (5, 10), (7, 5)]
pairs.sort(key=lambda x: x[1])
print(pairs)  # Outputs: [(3, 1), (1, 2), (7, 5), (5, 10)]

7. Nested Lambda Functions

Using lambdas within lambdas:

nested = lambda x: (lambda y: x + y)
add_five = nested(5)
print(add_five(3))  # Outputs: 8

8. Using Lambda with reduce()

Reducing a list using a lambda:

from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x * y, numbers)
print(result)  # Outputs: 120

9. Combining Lambdas

Combining multiple lambda functions:

multiply = lambda x: x * 2
add_ten = lambda x: x + 10
result = lambda x: add_ten(multiply(x))
print(result(5))  # Outputs: 20

10. Lambda as an Argument

Passing a lambda as an argument to another function:

def apply_func(func, value):
    return func(value)

result = apply_func(lambda x: x + 5, 10)
print(result)  # Outputs: 15

Summary

Lambda expressions in Python provide a concise way to create small, anonymous functions. They can be used in a variety of contexts, from simple arithmetic to more complex operations like sorting and filtering. While lambdas are powerful, their use should be limited to situations where they enhance code clarity, as overuse can make code harder to understand.

FAQ for Lambda Expressions in Python

What is a Lambda Expression in Python?

A lambda expression in Python is a way to create small, anonymous (unnamed) functions. These functions are often used for short, simple operations that can be defined in a single line of code.

How is a Lambda Expression Defined?

A lambda function is defined using the lambda keyword, followed by the arguments, a colon, and the expression.

lambda arguments: expression

Can Lambda Functions Have Multiple Arguments?

Yes, you can have multiple arguments separated by commas.

f = lambda x, y: x + y
print(f(2, 3))  # Output: 5

Can Lambda Functions Have Default Arguments?

No, lambda functions cannot have default argument values like standard Python functions defined with def.

How Do You Call a Lambda Function?

You can call a lambda function like any other function in Python.

f = lambda x: x + 1
print(f(2))  # Output: 3

Are Lambda Functions Faster Than Regular Functions?

Not necessarily. Lambda functions are generally used for their convenience and readability for simple operations. They are not optimized for speed compared to regular functions.

Can I Use a Lambda Function Inside a List Comprehension?

Yes, you can use a lambda function within a list comprehension or any other place where a function object is expected.

squared = [(lambda x: x*x)(x) for x in range(5)]

Can Lambda Functions Be Recursive?

No, lambda functions cannot be recursive because they are anonymous and cannot call themselves.

What are the Limitations of Lambda Functions?

  • They can only contain a single expression.
  • They cannot include statements like if, while, etc.
  • They are limited in terms of readability for complex logic.

Can I Assign a Name to a Lambda Function?

Yes, you can assign a lambda function to a variable, though doing so somewhat defeats the purpose of having an “anonymous” function.

f = lambda x: x + 1

This should cover the most commonly asked questions about lambda expressions in Python. Feel free to explore and experiment on your own to better understand their usage and limitations.