The filter()
function in Python is used to filter a sequence (like a list, tuple, or string) based on a condition provided by a function. It takes a function and an iterable as input and returns a filter object, which is an iterator containing only those elements of the iterable for which the function returns True
.
Syntax:
- function: A function that takes one argument and returns a boolean value (
True
orFalse
). The function is applied to each item in the iterable.- If the function returns
True
, the item is included in the result. - If the function returns
False
, the item is excluded.
- If the function returns
- iterable: The iterable (like a list, tuple, or set) that you want to filter.
The filter()
function does not modify the original iterable; it simply returns a new filter object containing the filtered elements.
Example Usage of filter()
:
1. Filtering even numbers from a list:
2. Using a lambda function to filter odd numbers:
You can use a lambda function (a small anonymous function) directly within filter()
to avoid defining a separate function.
3. Filtering out empty strings from a list:
4. Filtering based on multiple conditions:
You can also filter based on multiple conditions. For example, filtering numbers that are both positive and even:
Important Notes:
- The result of
filter()
is an iterator, so if you want to use the filtered result multiple times, you need to convert it into a list (or another iterable type) usinglist()
,tuple()
, or similar. - If the function argument is
None
,filter()
simply removes items that are “falsy” (i.e., items that evaluate toFalse
likeNone
,0
,False
,""
, and[]
).
Example with None
:
Summary:
filter()
is used to filter out elements from an iterable based on a given condition (function).- It returns an iterator, so converting it to a list or another iterable is often useful.
- The function passed to
filter()
should returnTrue
orFalse
for each item in the iterable.