Wie man in Python Inline-Funktionen erstellt

PythonPythonBeginner
Jetzt üben

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Introduction

In the world of Python programming, inline functions provide a powerful and concise way to create small, single-expression functions without the need for a formal function definition. These inline functions, known as lambda functions in Python, are particularly useful for simple operations and functional programming techniques. This tutorial will guide you through creating and using lambda functions to write more elegant and efficient Python code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/keyword_arguments("Keyword Arguments") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") python/FunctionsGroup -.-> python/recursion("Recursion") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-418721{{"Wie man in Python Inline-Funktionen erstellt"}} python/function_definition -.-> lab-418721{{"Wie man in Python Inline-Funktionen erstellt"}} python/keyword_arguments -.-> lab-418721{{"Wie man in Python Inline-Funktionen erstellt"}} python/lambda_functions -.-> lab-418721{{"Wie man in Python Inline-Funktionen erstellt"}} python/recursion -.-> lab-418721{{"Wie man in Python Inline-Funktionen erstellt"}} python/build_in_functions -.-> lab-418721{{"Wie man in Python Inline-Funktionen erstellt"}} python/data_collections -.-> lab-418721{{"Wie man in Python Inline-Funktionen erstellt"}} end

Understanding Lambda Functions Basics

What Are Lambda Functions

In Python, lambda functions are small, anonymous functions defined using the lambda keyword instead of the standard def statement. They are called "anonymous" because they do not require a name like traditional functions.

The basic syntax for a lambda function is:

lambda arguments: expression

Lambda functions are limited to a single expression and automatically return the result of that expression.

Creating Your First Lambda Function

Let's create and test some simple lambda functions:

  1. Open a new Python file in your code editor. Click on "File" > "New File" in the WebIDE and save it as lambda_basics.py in the /home/labex/project directory.

  2. Add the following code to create your first lambda function:

## A simple lambda function that squares a number
square = lambda x: x * x

## Testing the lambda function
result = square(5)
print(f"The square of 5 is: {result}")
  1. Run your code by opening a terminal (if not already open) and executing:
python3 ~/project/lambda_basics.py

You should see the output:

The square of 5 is: 25

Lambda Functions vs. Regular Functions

Let's compare lambda functions with their equivalent regular functions:

  1. Add the following code to your lambda_basics.py file:
## Regular function that adds two numbers
def add_regular(a, b):
    return a + b

## Equivalent lambda function
add_lambda = lambda a, b: a + b

## Testing both functions
print(f"Regular function: 3 + 5 = {add_regular(3, 5)}")
print(f"Lambda function: 3 + 5 = {add_lambda(3, 5)}")
  1. Run your code again:
python3 ~/project/lambda_basics.py

You should now see:

The square of 5 is: 25
Regular function: 3 + 5 = 8
Lambda function: 3 + 5 = 8

When to Use Lambda Functions

Lambda functions are most useful when:

  • You need a simple function for a short period
  • The function logic can be expressed in a single line
  • You want to pass a function as an argument to another function

Let's create one more example with multiple parameters:

  1. Add the following code to your lambda_basics.py file:
## Lambda function with multiple parameters
calculate = lambda x, y, z: x * y + z

## Testing with different values
result1 = calculate(2, 3, 4)
result2 = calculate(5, 2, 1)

print(f"2 * 3 + 4 = {result1}")
print(f"5 * 2 + 1 = {result2}")
  1. Run your updated code:
python3 ~/project/lambda_basics.py

You should see additional output:

2 * 3 + 4 = 10
5 * 2 + 1 = 11

Summary of Lambda Basics

Lambda functions are ideal for creating simple, one-line functions. They provide a concise way to write code when you don't need a full function definition. In the next step, we'll explore how to use lambda functions with Python's built-in functions for more powerful operations.

Using Lambda with Built-in Functions

Lambda functions become particularly powerful when combined with Python's built-in functions like map(), filter(), and sorted(). These combinations allow you to write efficient code for data transformation and manipulation.

The map() Function with Lambda

The map() function applies a given function to each item in an iterable (like a list) and returns a map object with the results.

  1. Create a new file named lambda_builtin.py in the /home/labex/project directory.

  2. Add the following code to demonstrate using map() with lambda:

## Using map() with a lambda function to square each number in a list
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))

print("Original numbers:", numbers)
print("Squared numbers:", squared_numbers)
  1. Run your code:
python3 ~/project/lambda_builtin.py

You should see:

Original numbers: [1, 2, 3, 4, 5]
Squared numbers: [1, 4, 9, 16, 25]

The filter() Function with Lambda

The filter() function creates a new iterable with elements that satisfy a condition (function returns True).

  1. Add the following code to your lambda_builtin.py file:
## Using filter() with a lambda function to find even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print("All numbers:", numbers)
print("Even numbers:", even_numbers)

## Using filter() to find names that start with 'J'
names = ["Alice", "Bob", "John", "Jane", "Michael", "Jessica"]
j_names = list(filter(lambda name: name.startswith('J'), names))

print("All names:", names)
print("Names starting with J:", j_names)
  1. Run your updated code:
python3 ~/project/lambda_builtin.py

You should see additional output:

All numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even numbers: [2, 4, 6, 8, 10]
All names: ['Alice', 'Bob', 'John', 'Jane', 'Michael', 'Jessica']
Names starting with J: ['John', 'Jane', 'Jessica']

The sorted() Function with Lambda

The sorted() function allows you to sort iterables using a custom key function, which is where lambda functions are very useful.

  1. Add the following code to your lambda_builtin.py file:
## Using sorted() with lambda to sort by the second element of tuples
pairs = [(1, 5), (3, 2), (5, 7), (2, 9), (4, 1)]
sorted_by_second = sorted(pairs, key=lambda pair: pair[1])

print("Original pairs:", pairs)
print("Sorted by second element:", sorted_by_second)

## Using sorted() with lambda to sort strings by length
words = ["apple", "banana", "cherry", "date", "elderberry", "fig"]
sorted_by_length = sorted(words, key=lambda word: len(word))

print("Original words:", words)
print("Sorted by length:", sorted_by_length)
  1. Run your updated code:
python3 ~/project/lambda_builtin.py

You should see additional output:

Original pairs: [(1, 5), (3, 2), (5, 7), (2, 9), (4, 1)]
Sorted by second element: [(4, 1), (3, 2), (1, 5), (5, 7), (2, 9)]
Original words: ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']
Sorted by length: ['fig', 'date', 'apple', 'cherry', 'banana', 'elderberry']

Combining Multiple Lambda Functions

You can also chain or combine multiple operations using lambda functions:

  1. Add the following code to your lambda_builtin.py file:
## Combining map and filter with lambda functions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

## First square the numbers, then filter for values greater than 20
result = list(filter(lambda x: x > 20, map(lambda x: x**2, numbers)))

print("Original numbers:", numbers)
print("Squared numbers > 20:", result)
  1. Run your updated code:
python3 ~/project/lambda_builtin.py

You should see additional output:

Original numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Squared numbers > 20: [25, 36, 49, 64, 81, 100]

Lambda functions with built-in functions like map(), filter(), and sorted() provide a powerful way to process data with minimal code. In the next step, we'll explore more practical applications of lambda functions.

Practical Lambda Applications

In this step, we'll explore some practical applications of lambda functions, including their use with conditional logic and how to use them in real-world scenarios.

Lambda with Conditional Expressions

Lambda functions can include conditional expressions using Python's ternary operator syntax: x if condition else y.

  1. Create a new file named lambda_practical.py in the /home/labex/project directory.

  2. Add the following code to demonstrate conditional lambda functions:

## Lambda with conditional expression
get_status = lambda score: "Pass" if score >= 60 else "Fail"

## Test the function with different scores
scores = [45, 90, 60, 30, 75]

for score in scores:
    status = get_status(score)
    print(f"Score: {score}, Status: {status}")
  1. Run your code:
python3 ~/project/lambda_practical.py

You should see:

Score: 45, Status: Fail
Score: 90, Status: Pass
Score: 60, Status: Pass
Score: 30, Status: Fail
Score: 75, Status: Pass

Creating a Simple Calculator with Lambda

Lambda functions are perfect for creating simple utility functions like a calculator:

  1. Add the following code to your lambda_practical.py file:
## Creating a calculator using lambda functions
operations = {
    'add': lambda x, y: x + y,
    'subtract': lambda x, y: x - y,
    'multiply': lambda x, y: x * y,
    'divide': lambda x, y: x / y if y != 0 else "Cannot divide by zero"
}

## Test the calculator
a, b = 10, 2

for operation, func in operations.items():
    result = func(a, b)
    print(f"{a} {operation} {b} = {result}")

## Test division by zero
print(f"10 divide 0 = {operations['divide'](10, 0)}")
  1. Run your code:
python3 ~/project/lambda_practical.py

You should see additional output:

10 add 2 = 12
10 subtract 2 = 8
10 multiply 2 = 20
10 divide 2 = 5.0
10 divide 0 = Cannot divide by zero

Data Transformation with Lambda

Lambda functions are excellent for transforming data structures:

  1. Add the following code to your lambda_practical.py file:
## Processing a list of dictionaries with lambda
employees = [
    {'name': 'Alice', 'salary': 90000, 'department': 'Engineering'},
    {'name': 'Bob', 'salary': 75000, 'department': 'Marketing'},
    {'name': 'Charlie', 'salary': 60000, 'department': 'Engineering'},
    {'name': 'David', 'salary': 85000, 'department': 'HR'},
    {'name': 'Eve', 'salary': 120000, 'department': 'Engineering'}
]

## Find engineering employees and sort them by salary
engineering_employees = sorted(
    filter(lambda emp: emp['department'] == 'Engineering', employees),
    key=lambda emp: emp['salary'],
    reverse=True
)

print("Engineering employees (highest salary first):")
for employee in engineering_employees:
    print(f"  {employee['name']}: ${employee['salary']}")

## Calculate average salary
average_salary = sum(map(lambda emp: emp['salary'], employees)) / len(employees)
print(f"\nAverage salary: ${average_salary:.2f}")

## Find employees with above-average salary
above_average = list(filter(lambda emp: emp['salary'] > average_salary, employees))
print(f"\nEmployees with above-average salary:")
for employee in above_average:
    print(f"  {employee['name']}: ${employee['salary']} ({employee['department']})")
  1. Run your updated code:
python3 ~/project/lambda_practical.py

You should see additional output:

Engineering employees (highest salary first):
  Eve: $120000
  Alice: $90000
  Charlie: $60000

Average salary: $86000.00

Employees with above-average salary:
  Alice: $90000 (Engineering)
  Eve: $120000 (Engineering)

Lambda as Event Handlers with Tkinter

Lambda functions are commonly used as event handlers in GUI applications. Let's create a simple Tkinter application to demonstrate this:

  1. Add the following code to a new file named lambda_gui.py in the /home/labex/project directory:
import tkinter as tk

## Create a simple calculator GUI
def create_calculator():
    ## Create the main window
    window = tk.Tk()
    window.title("Lambda Calculator")
    window.geometry("300x200")

    ## Create input fields
    num1_label = tk.Label(window, text="First Number:")
    num1_label.pack(pady=5)
    num1_entry = tk.Entry(window)
    num1_entry.pack(pady=5)

    num2_label = tk.Label(window, text="Second Number:")
    num2_label.pack(pady=5)
    num2_entry = tk.Entry(window)
    num2_entry.pack(pady=5)

    result_label = tk.Label(window, text="Result: ")
    result_label.pack(pady=10)

    ## Create button frame
    button_frame = tk.Frame(window)
    button_frame.pack(pady=10)

    ## Create operation buttons using lambda functions
    operations = ['+', '-', '*', '/']

    for op in operations:
        ## Using lambda for button click handlers
        ## Use default parameter to avoid late binding issues
        button = tk.Button(
            button_frame,
            text=op,
            width=3,
            command=lambda op=op: calculate(op, num1_entry, num2_entry, result_label)
        )
        button.pack(side=tk.LEFT, padx=5)

    window.mainloop()

def calculate(operation, num1_entry, num2_entry, result_label):
    try:
        num1 = float(num1_entry.get())
        num2 = float(num2_entry.get())

        ## Create operations dictionary with lambda functions
        operations = {
            '+': lambda x, y: x + y,
            '-': lambda x, y: x - y,
            '*': lambda x, y: x * y,
            '/': lambda x, y: x / y if y != 0 else "Cannot divide by zero"
        }

        result = operations[operation](num1, num2)
        result_label.config(text=f"Result: {result}")
    except ValueError:
        result_label.config(text="Please enter valid numbers")
    except Exception as e:
        result_label.config(text=f"Error: {str(e)}")

## Main code to run the calculator
if __name__ == "__main__":
    print("This is a GUI calculator example using lambda functions.")
    print("To run it in a GUI environment, you would call create_calculator()")
    print("Due to this being a terminal environment, we'll only show the code.")
  1. Let's view the code to understand how lambda functions are used in GUI applications:
cat ~/project/lambda_gui.py

Now you've seen how lambda functions can be applied in various practical scenarios, from simple data processing to more complex applications like GUIs and data transformation.

Advanced Lambda Techniques

In this final step, we'll explore some advanced techniques using lambda functions, including nested lambdas, closures, and higher-order functions.

Returning Lambda Functions from Functions

Lambda functions can be created and returned from other functions, allowing for dynamic function creation:

  1. Create a new file named lambda_advanced.py in the /home/labex/project directory.

  2. Add the following code:

## Function that returns a lambda function
def create_multiplier(factor):
    """Returns a function that multiplies its input by the given factor."""
    return lambda x: x * factor

## Create specific multiplier functions
double = create_multiplier(2)
triple = create_multiplier(3)
quadruple = create_multiplier(4)

## Test the multiplier functions
number = 10
print(f"Original number: {number}")
print(f"Double: {double(number)}")
print(f"Triple: {triple(number)}")
print(f"Quadruple: {quadruple(number)}")
  1. Run your code:
python3 ~/project/lambda_advanced.py

You should see:

Original number: 10
Double: 20
Triple: 30
Quadruple: 40

Function Composition with Lambda

We can compose functions using lambda to create a pipeline of operations:

  1. Add the following code to your lambda_advanced.py file:
## Function composition using lambda
def compose(f, g):
    """Returns a function that applies f after g."""
    return lambda x: f(g(x))

## Create component functions
square = lambda x: x * x
increment = lambda x: x + 1
decrement = lambda x: x - 1

## Create composite functions
square_then_increment = compose(increment, square)
increment_then_square = compose(square, increment)
complex_operation = compose(square, compose(increment, square))

## Test the composite functions
value = 5
print(f"\nOriginal value: {value}")
print(f"square_then_increment: {square_then_increment(value)}")  ## (5² = 25) + 1 = 26
print(f"increment_then_square: {increment_then_square(value)}")  ## (5 + 1)² = 36
print(f"complex_operation: {complex_operation(value)}")          ## ((5² = 25) + 1)² = 676
  1. Run your updated code:
python3 ~/project/lambda_advanced.py

You should see additional output:

Original value: 5
square_then_increment: 26
increment_then_square: 36
complex_operation: 676

Recursive Lambda Functions

Creating true recursive lambda functions is challenging in Python due to the way lambdas are defined. However, we can use a trick with the Y combinator to create recursive lambda functions:

  1. Add the following code to your lambda_advanced.py file:
## Y combinator for creating recursive lambda functions
Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))

## Creating a recursive factorial function using lambda and the Y combinator
factorial = Y(lambda f: lambda n: 1 if n <= 0 else n * f(n - 1))

## Test the recursive factorial function
for i in range(6):
    print(f"factorial({i}) = {factorial(i)}")

## Creating a recursive Fibonacci function using lambda and the Y combinator
fibonacci = Y(lambda f: lambda n: n if n <= 1 else f(n-1) + f(n-2))

## Test the recursive Fibonacci function
print("\nFibonacci sequence:")
for i in range(10):
    print(f"fibonacci({i}) = {fibonacci(i)}")
  1. Run your updated code:
python3 ~/project/lambda_advanced.py

You should see additional output:

factorial(0) = 1
factorial(1) = 1
factorial(2) = 2
factorial(3) = 6
factorial(4) = 24
factorial(5) = 120

Fibonacci sequence:
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(2) = 1
fibonacci(3) = 2
fibonacci(4) = 3
fibonacci(5) = 5
fibonacci(6) = 8
fibonacci(7) = 13
fibonacci(8) = 21
fibonacci(9) = 34

Lambda with Partial Function Application

Partial function application allows you to create new functions by pre-filling some arguments of existing functions:

  1. Add the following code to your lambda_advanced.py file:
from functools import partial

## Original function with multiple parameters
def power(base, exponent):
    return base ** exponent

## Creating specialized functions using partial and lambda
square = partial(power, exponent=2)
cube = partial(power, exponent=3)

## Alternative approach using lambda
square_lambda = lambda x: power(x, 2)
cube_lambda = lambda x: power(x, 3)

## Test both approaches
number = 4
print(f"\nOriginal number: {number}")
print(f"square (partial): {square(number)}")
print(f"cube (partial): {cube(number)}")
print(f"square (lambda): {square_lambda(number)}")
print(f"cube (lambda): {cube_lambda(number)}")

## Partial application with multiple pre-filled arguments
def format_string(prefix, content, suffix):
    return f"{prefix}{content}{suffix}"

## Create specialized formatters
html_paragraph = partial(format_string, "<p>", suffix="</p>")
html_div = partial(format_string, "<div>", suffix="</div>")

## Test specialized formatters
content = "Hello, World!"
print(f"\nOriginal content: {content}")
print(f"HTML paragraph: {html_paragraph(content)}")
print(f"HTML div: {html_div(content)}")
  1. Run your updated code:
python3 ~/project/lambda_advanced.py

You should see additional output:

Original number: 4
square (partial): 16
cube (partial): 64
square (lambda): 16
cube (lambda): 64

Original content: Hello, World!
HTML paragraph: <p>Hello, World!</p>
HTML div: <div>Hello, World!</div>

These advanced techniques showcase the flexibility and power of lambda functions in Python. By combining lambda functions with higher-order functions, functional composition, and partial application, you can create concise and elegant solutions to complex problems.

Summary

In this lab, you have learned how to create and use inline functions (lambda functions) in Python, progressing from basic concepts to advanced techniques.

Here's what you've accomplished:

  1. Basic Lambda Functions - You learned the syntax and basic usage of lambda functions, compared them with regular functions, and understood when to use them.

  2. Lambda with Built-in Functions - You explored how to combine lambda functions with Python's built-in functions like map(), filter(), and sorted() to perform powerful data transformations efficiently.

  3. Practical Lambda Applications - You implemented practical examples including conditional expressions, a simple calculator, and data transformation techniques to process collections of data.

  4. Advanced Lambda Techniques - You explored higher-order functions, function composition, recursive lambda functions using the Y combinator, and partial function application to solve complex problems concisely.

Lambda functions are a powerful tool in Python programming, allowing for concise, functional programming styles. While they are best suited for simple operations, their ability to be passed as arguments and returns from functions makes them incredibly versatile for a wide range of applications.

By mastering lambda functions, you've added an important tool to your Python programming toolkit that will help you write more elegant and efficient code.