5.5 Lambda Functions

5.5 Lambda Functions

We learn to create small, anonymous functions with the lambda keyword, ideal for simple operations and use in higher-order functions.

Lambda functions (or anonymous functions) are a concise way to define a small, single-use function. They do not use the `def` keyword and can only contain one expression, the value of which is automatically returned.
The syntax is: `lambda arguments: expression`.
`lambda` functions are particularly useful when you need a simple function for a short period, especially as an argument to higher-order functions (like `sorted()`, `map()`, `filter()`).
# Lambda function for addition
addition = lambda a, b: a + b
print(f"Sum with lambda (5, 3): {addition(5, 3)}")

# Using lambda for sorting
points_list = [(1, 5), (3, 2), (2, 8), (4, 1)]
# key=lambda item: item[1] means: sort based on the second element
sorted_list = sorted(points_list, key=lambda item: item[1])
print(f"Sorted list (based on y): {sorted_list}")

# Using lambda with filter()
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even numbers with filter: {evens}")

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.