Sharing is caring 🙂

In Python, a lambda expression is a small, anonymous function that can be defined without a name. These expressions are often used in situations where a function is required for a short period of time, such as in the arguments of other functions like map() and filter(). Lambda expressions are defined using the keyword “lambda”, followed by one or more arguments, a colon, and an expression.

The basic syntax for a lambda expression is as follows:

lambda arguments: expression

For example, a lambda expression that takes a single argument, x, and returns its square can be written as:

lambda x: x**2

This lambda expression can be assigned to a variable and used just like any other function. For example:

square = lambda x: x**2 print(square(5)) 
# prints 25

In addition to being simple and easy to use, lambda expressions can also be useful for improving code readability, particularly in situations where a small, single-use function is needed.

In this tutorial, you’ll learn more about lambda expressions and how to use them with the map() and filter() functions in Python.

Using Lambda Expressions with Map

The map() function in Python is used to apply a given function to all items in an input list. This function takes two arguments: a function and an iterable. The function is applied to each item in the iterable, and a new iterable containing the results is returned.

Lambda expressions can be used as the function argument in the map() function. This can be useful for situations where a simple, one-line function is needed to transform the items in the iterable.

For example, consider the following list of numbers

numbers = [1, 2, 3, 4, 5]

To square each number in this list, we can use the following code

squared_numbers = map(lambda x: x**2, numbers)

This code creates a new iterable, squared_numbers, which contains the square of each number in the original list.

Another example is to convert a list of string into uppercase by using the following code:

uppercase_strings = map(lambda x: x.upper(), strings)

This code creates a new iterable, uppercase_strings, which contains the uppercase version of each string in the original list.

The map() function returns an iterator, so if you want to see the results you can use the list() function or convert it to set, dict…

Using Lambda Expressions with Filter

The filter() function in Python is used to filter a given iterable based on a certain condition. This function takes two arguments: a function and an iterable. The function is applied to each item in the iterable, and a new iterable containing only the items for which the function returned True is returned.

Lambda expressions can be used as the function argument in the filter() function. This can be useful for situations where a simple, one-line function is needed to determine which items in the iterable should be included in the filtered result.

For example, consider the following list of numbers:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

To filter out even numbers from this list, we can use the following code:

even_numbers = filter(lambda x: x % 2 == 0, numbers)

This code creates a new iterable, even_numbers, which contains only the even numbers from the original list.

Another example is to filter out the words that have a specific letter from a list of strings:

specific_letter_words = filter(lambda x: 'a' in x, words)

This code creates a new iterable, specific_letter_words, which contains only the words that contain letter ‘a’ from the original list.

Combining Map and Filter with Lambda Expressions

It is possible to use both map() and filter() functions together in a single line of code, by chaining them together. This can be useful for situations where multiple operations need to be performed on an iterable, and the results of one operation are used as the input for the next.

For example, consider the following list of numbers:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

To filter out even numbers and then square the remaining numbers, we can use the following code:

squared_odd_numbers = map(lambda x: x**2, filter(lambda x: x % 2 != 0, numbers))

This code first filters out the even numbers using filter(lambda x: x % 2 != 0, numbers), and then squares the remaining odd numbers using map(lambda x: x**2, …). The result is a new iterable, squared_odd_numbers, which contains the squares of the odd numbers from the original list.

Another example is to filter out the words that have a specific letter and then convert the remaining words to uppercase:

uppercase_specific_letter_words = map(lambda x: x.upper(), filter(lambda x: 'a' in x, words))

This code first filters out the words that don’t contain letter ‘a’ using filter(lambda x: ‘a’ in x, words), and then converts the remaining words to uppercase using map(lambda x: x.upper(), …). The result is a new iterable, uppercase_specific_letter_words, which contains the uppercase version of the words that contain letter ‘a’ from the original list. The order of filter and map is important since the result of one function is used as an input for the other.

Real-World Examples of Lambda Expressions, Map, and Filter Functions

Lambda expressions, map(), and filter() functions can be used in many real-world scenarios, for example:

  1. Data Processing: You can use lambda expressions, map(), and filter() to process and clean large datasets. For example, you can use filter() to remove duplicate or null values from a dataset, and map() to convert all the strings in a column to uppercase or lowercase.
  2. Web Scraping: You can use these functions to extract specific information from web pages or HTML documents. For example, you can use filter() to select specific HTML tags, and map() to extract the text contents of those tags.
  3. Machine Learning: You can use these functions to preprocess your data before feeding it to a machine learning model. For example, you can use map() to normalize numerical features, and filter() to select specific examples based on certain conditions.
  4. Image Processing: You can use these functions to process images, for example, you can use map() to apply a certain effect to all pixels in an image and filter() to select only certain pixels based on their color.
  5. Natural Language Processing: You can use these functions to process text data, for example, you can use map() to tokenize a text and filter() to remove stop words from a list of tokens.

Here is an example of using these function in a real-world scenario:

import re

emails = ['user@example.com', 'user.name@example.com', 'user_name@example.com', 'user@sub.example.com']
valid_emails = list(filter(lambda x: re.match("^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,}$", x), emails))

This code uses a regular expression with the filter() function to select only the emails that match the pattern of a valid email address, and saves the valid email addresses in the valid_emails list.

Lambda Expression FAQ

Q: What is a lambda expression in Python? A: A lambda expression is a small, anonymous function that can be defined without a name in Python. These expressions are often used in situations where a function is required for a short period of time, such as in the arguments of other functions like map() and filter().

Q: How do I use a lambda expression? A: Lambda expressions are defined using the keyword “lambda”, followed by one or more arguments, a colon, and an expression. For example, a lambda expression that takes a single argument, x, and returns its square can be written as: lambda x: x**2. You can then assign this lambda expression to a variable and use it like any other function.

Q: What is the difference between a lambda expression and a regular function? A: The main difference between a lambda expression and a regular function is that lambda expressions are anonymous and do not have a name, whereas regular functions have a name and can be reused throughout the code. Lambda expressions are typically used for small, single-use functions, while regular functions are used for more complex operations that need to be reused.

Q: Can I use a lambda expression with the map() and filter() functions? A: Yes, lambda expressions can be used as the function argument in the map() and filter() functions in Python. This can be useful for situations where a simple, one-line function is needed to transform or filter items in an iterable.

Q: Can I use a lambda expression inside a list comprehension? A: Yes, lambda expressions can also be used inside a list comprehension, to perform a certain operation on each item in an iterable. It’s a more readable and concised version of using map() or filter() with a lambda function.

Q: Can I use a lambda expression in place of a regular function? A: Lambda expressions and regular functions can be used interchangeably in most cases, but lambda expressions are typically used for small, single-use functions, while regular functions are used for more complex operations that need to be reused. It’s important to choose the right tool for the job, and make sure that your code is readable and maintainable.

Sharing is caring 🙂