Lambda Functions in Python

Lambda functions, also known as anonymous functions, are a concise way to create small, one-line functions without using the def keyword. They are useful for writing quick, throwaway functions or for passing as arguments to higher-order functions. In this topic, we'll explore lambda functions in detail, covering everything from basic syntax to advanced techniques.

Basics of Lambda Functions

What are Lambda Functions?

Lambda functions are small, anonymous functions that can have any number of parameters but can only have one expression.

Basic Syntax

The basic syntax of a lambda function in Python is as follows:

				
					lambda parameters: expression
				
			

Example

				
					# Example of a lambda function
add = lambda x, y: x + y
print(add(3, 5))  # Output: 8
				
			

Using Lambda Functions

Assigning Lambda Functions to Variables

You can assign lambda functions to variables for later use, similar to regular functions.

				
					# Example of assigning a lambda function to a variable
multiply = lambda x, y: x * y
print(multiply(3, 5))  # Output: 15
				
			

Using Lambda Functions with Built-in Functions

Lambda functions are commonly used with built-in functions like map(), filter(), and reduce().

				
					# Example of using lambda function with map()
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)
print(list(squared))  # Output: [1, 4, 9, 16, 25]
				
			

Using Lambda Functions with Sorting

Lambda functions can be used as key functions for sorting.

				
					# Example of using lambda function for sorting
students = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 20},
    {"name": "Charlie", "age": 30}
]
students.sort(key=lambda x: x["age"])
print(students)  # Output: [{'name': 'Bob', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]
				
			

Advanced Techniques

Currying with Lambda Functions

Currying is a technique where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument.

Using Lambda Functions in Higher-order Functions

Lambda functions are often used as arguments to higher-order functions like sorted(), map(), filter(), and reduce().

Lambda functions provide a concise and powerful way to define small functions in Python without the need for the def keyword. By understanding the basic syntax of lambda functions and how to use them with built-in functions, sorting, and higher-order functions, you can write more expressive and concise code. Remember to use lambda functions judiciously, especially in situations where readability and maintainability are not compromised. Practice using lambda functions in various contexts to enhance your programming skills. Happy Coding!❤️

Table of Contents