Lambda Expression in Python
Lambda Function Definition and Purpose
Lambda functions, also known as anonymous functions, are small, inline functions that can have any number of arguments but only one expression. They are particularly useful when you need a simple function for a short period in your code, eliminating the need for a formal function definition.
The primary purpose of lambda functions is to provide a concise and readable way to define small, one-off functions without the overhead of defining a named function using the def keyword.
- Syntax of Lambda Functions
The syntax of a lambda function is straightforward. It starts with the lambda keyword, followed by the parameters, a colon (:), and the expression. Here’s the general syntax:
lambda parameters: expression
- Use Cases and Examples
Lambda functions can be used in various scenarios where a simple, short-lived function is required. Let’s explore some common use cases along with examples:
- Sorting a List of Tuples:
Lambda functions are commonly used with built-in functions like sorted() or sort() to provide custom sorting criteria. For instance, suppose we have a list of tuples representing students’ names and their corresponding scores. We can sort this list based on the scores using a lambda function:
Get Dipti Domadiya’s stories in your inbox
Join Medium for free to get updates from this writer.
students = [(‘Amar’, 90), (‘Bansi’, 85), (‘Chhaya’, 95)]
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
print(sorted_students)
Output: [(‘Chhaya’, 95), (‘Amar’, 90), (‘Bansi’, 85)]
2. Filtering a List:
Lambda functions are often used with the filter() function to create a new list containing only elements that satisfy a certain condition. For example, let’s filter out even numbers from a list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Output: [2, 4, 6, 8, 10]
3. Mapping Values:
Lambda functions are also commonly used with the map() function to apply a function to every element in a sequence. For instance, let’s square each number in a list:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
Output: [1, 4, 9, 16, 25]
Lambda functions offer a concise and readable way to define simple functions on-the-fly, making them invaluable tools for certain programming tasks in Python. However, it’s essential to use them judiciously and consider readability and maintainability when deciding whether to use lambda functions or traditional named functions.






