What is lambda and filter in Python examples?

Given a list of numbers, find all numbers divisible by 13.

Input : my_list = [12, 65, 54, 39, 102, 
                     339, 221, 50, 70]
Output : [65, 39, 221]

We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is without a name.

The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True.

Lambda and filter are two useful built-in functions in Python that allow you to manipulate and filter data.

Lambda is a function that can be defined in one line of code and doesn't require a name. It is commonly used when you need a simple function for a specific task and you don't want to define a full function. The syntax of a lambda function is lambda argument: expression, where argument is the input to the function and expression is the output. Here's an example: 

# Define a lambda function that squares its input
square = lambda x: x**2

# Use the lambda function to square a number
result = square(5)

print(result) # Output: 25

Filter, on the other hand, is a function that can be used to filter a sequence of data based on a specific condition. It takes two arguments: a function and a sequence. The function is used to evaluate each element in the sequence and return True or False, and the sequence is the data that you want to filter. Here's an example: 

# Define a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter to return only the even numbers from the list
result = list(filter(lambda x: x % 2 == 0, numbers))

print(result) # Output: [2, 4, 6, 8, 10]

In this example, the lambda function checks if each number in the list is even by using the modulo operator (%). Filter then returns a new list with only the even numbers.

Submit Your Programming Assignment Details