lambda: Anonymous, single-line functions for quick tasks.

Python Lambda Functions

Python lambda functions are small, anonymous functions created using the lambda keyword. These functions are typically one-liners designed for simple operations, often used as arguments in higher-order functions like map(), filter(), or sorted(). Lambda functions are also known as “inline functions” because they’re usually written where they’re used, without formally defining a function with def.

Syntax

The basic syntax of a lambda function:
lambda arguments: expression
- arguments: The inputs to the lambda function, which can be one or more parameters separated by commas.
- expression: A single expression that the lambda function returns.

Example 1: Basic Lambda Function

Here’s a simple example of a lambda function that adds two numbers.
add = lambda x, y: x + y
print(add(3, 5))
Output:
8

Example 2: Lambda Function with map()

Lambda functions are often used with map() to apply an operation to each item in an iterable, such as a list.
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)
Output:
[1, 4, 9, 16]

Example 3: Using Lambda with filter()

Lambda functions are commonly paired with filter() to select items from an iterable based on a condition.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Output:
[2, 4, 6]

Example 4: Sorting with Lambda in sorted()

You can use lambda functions as a key argument in sorted() to sort complex data structures like lists of tuples or dictionaries.
pairs = [(1, 'apple'), (2, 'orange'), (3, 'banana')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)
Output:
[(1, 'apple'), (3, 'banana'), (2, 'orange')]

Example 5: Lambda with Default Arguments

Lambda functions can also include default parameters, which allows for flexible functionality without defining multiple functions.
multiply = lambda x, y=2: x * y
print(multiply(3))       # Uses default y=2
print(multiply(3, 4))    # Uses provided y=4
Output:
6
12

Python Lambda Functions: Advanced Examples

Example 6: Lambda for Conditional Expressions

Lambda functions can handle conditional expressions to return values based on conditions.
is_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(is_even(4))   # Output: Even
print(is_even(5))   # Output: Odd

Example 7: Using Lambda with reduce() for Accumulation

Lambda functions work well with reduce() from the `functools` module to apply an operation to an iterable and reduce it to a single result.
from functools import reduce

numbers = [1, 2, 3, 4]
sum_all = reduce(lambda x, y: x + y, numbers)
print(sum_all)  # Output: 10

Example 8: Lambda for Sorting a List of Dictionaries

Lambda functions are useful for creating custom sort keys, as seen in sorting lists of dictionaries.
students = [
    {"name": "Alice", "grade": 85},
    {"name": "Bob", "grade": 90},
    {"name": "Charlie", "grade": 80}
]

sorted_students = sorted(students, key=lambda student: student["grade"])
print(sorted_students)
Output ( sorted based on grade )
[
    {'name': 'Charlie', 'grade': 80},
    {'name': 'Alice', 'grade': 85},
    {'name': 'Bob', 'grade': 90}
]

Example 9: Lambda to Find Max/Min in Nested Lists

Use lambda functions with max() and min() to identify values based on a custom criterion.
points = [(2, 5), (3, 1), (4, 7), (1, 9)]
highest_y = max(points, key=lambda point: point[1])
print(highest_y)  # Output: (1, 9)

Example 10: Lambda with any() and all()

You can combine lambda functions with any() and all() to apply conditions across iterables.
numbers = [1, 2, 3, 4]
print(any(map(lambda x: x % 2 == 0, numbers)))  # Output: True (because 2 and 4 are even)
print(all(map(lambda x: x > 0, numbers)))       # Output: True (all numbers are positive)

Example 11: Lambda with Nested Lambda Functions

Lambda functions can even be nested, though this may reduce readability.
multiply = lambda x: lambda y: x * y
double = multiply(2)
print(double(5))  # Output: 10

Example 12: Lambda in Dictionaries

Lambda functions can be stored in dictionaries for quick command or function mappings.
operations = {
    "add": lambda x, y: x + y,
    "subtract": lambda x, y: x - y,
    "multiply": lambda x, y: x * y
}

print(operations["add"](5, 3))       # Output: 8
print(operations["multiply"](5, 3))  # Output: 15

Use Cases for Lambda Functions

  • Quick One-Liner Functions: Ideal for small operations where defining a function would be overkill.
  • Higher-Order Functions: Lambda functions work well with functions like map(), filter(), and reduce() for functional programming tasks.
  • Sorting and Grouping Data: Use in sorted() or groupby() for custom sorting or grouping without needing separate helper functions.
Lambda functions provide flexibility and conciseness in Python programming. While powerful, they are best used for simple, short tasks since their anonymous nature can reduce readability for more complex operations.
All Built in Functions in Python slice()

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer