The filter() Function
What is
The
Syntax:
Example: Using
Output:
In this example, the
Example: Using
Output:
Again, using a
What is
filter()?The
filter() function filters elements from an iterable based on a condition defined by a function. It returns only the elements for which the function returns True.Syntax:
filter(function, iterable)
Example: Using
filter() to Filter Even Numbersdef is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # Convert the filter object to a list
Output:
[2, 4, 6]
In this example, the
filter() function keeps only the even numbers from the list.Example: Using
lambda with filter()numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
Output:
[2, 4, 6]
Again, using a
lambda function simplifies the code.The reduce() Function
What is r
The
Syntax
To use
Example: Using
Output:
In this example,
Example: Using
Output:
Using
What is r
educe()?The
reduce() function from the functools module applies a function cumulatively to the items of an iterable, reducing the iterable to a single value.Syntax
reduce(function, iterable)
To use
reduce(), you need to import it from the functools module.Example: Using
reduce() to Sum a Listfrom functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
total_sum = reduce(add, numbers)
print(total_sum)
Output:
15
In this example,
reduce() adds each number in the list to the next, resulting in the sum of all numbers.Example: Using
lambda with reduce()from functools import reduce
numbers = [1, 2, 3, 4, 5]
total_sum = reduce(lambda x, y: x + y, numbers)
print(total_sum)
Output:
15
Using
lambda with reduce() simplifies the function definition.👍3❤1
New users check pinned message 📌
👍6
Are you dead?
👎27👨💻11👍8❤6😁5💯2🗿2🤗1
If you are alive the comment your name👇
👍27❤13🔥3