Certainly! Let’s create a simple example to illustrate how to use lambda
, map
, and filter
in Python.
Let’s say we have a list of numbers and we want to perform some operations on them using map
and filter
along with lambda
functions.
# Example list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Using map and lambda to square each number in the list
squared_numbers = list(map(lambda x: x**2, numbers))
print("Squared numbers:", squared_numbers)
# Using filter and lambda to keep only even numbers in the list
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", even_numbers)
In this example:
- We start with a list of numbers from 1 to 10.
- We use the
map
function along with a lambda function to square each number in the list. The lambda functionlambda x: x**2
takes an inputx
and returns its square. - We use the
filter
function along with a lambda function to keep only the even numbers in the list. The lambda functionlambda x: x % 2 == 0
checks if a number is even (i.e., its remainder when divided by 2 is 0).
When you run this code, you will get the following output:
Squared numbers: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Even numbers: [2, 4, 6, 8, 10]
This demonstrates how you can use lambda
functions in combination with map
and filter
to perform operations on lists in Python.