Sunday, January 12, 2025
HomeComputer Sciencefilter() in python

filter() in python

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:

python
filter(function, iterable)
  • function: A function that takes one argument and returns a boolean value (True or False). 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.
  • 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:

python
# Define a function that returns True for even numbers
def is_even(num):
return num % 2 == 0

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

# Use filter() to get only the even numbers
even_numbers = filter(is_even, numbers)

# Convert the result to a list and print
print(list(even_numbers)) # Output: [2, 4, 6, 8, 10]

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.

python
# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter() with a lambda function to filter out odd numbers
odd_numbers = filter(lambda x: x % 2 != 0, numbers)

# Convert the result to a list and print
print(list(odd_numbers)) # Output: [1, 3, 5, 7, 9]

3. Filtering out empty strings from a list:

python
# List containing empty strings
words = ["apple", "", "banana", " ", "cherry", ""]

# Use filter() to remove empty strings
non_empty_words = filter(lambda word: word.strip() != "", words)

# Convert the result to a list and print
print(list(non_empty_words)) # Output: ['apple', 'banana', 'cherry']

4. Filtering based on multiple conditions:

You can also filter based on multiple conditions. For example, filtering numbers that are both positive and even:

python
# List of numbers
numbers = [-10, -5, 0, 2, 4, 6, 8, 10]

# Use filter() to get positive even numbers
positive_even_numbers = filter(lambda x: x > 0 and x % 2 == 0, numbers)

# Convert the result to a list and print
print(list(positive_even_numbers)) # Output: [2, 4, 6, 8, 10]

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) using list(), tuple(), or similar.
  • If the function argument is None, filter() simply removes items that are “falsy” (i.e., items that evaluate to False like None, 0, False, "", and []).

Example with None:

python
# List of values
values = [0, 1, 2, '', False, None, 3]

# Use filter() to remove falsy values
filtered_values = filter(None, values)

# Convert the result to a list and print
print(list(filtered_values)) # Output: [1, 2, 3]

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 return True or False for each item in the iterable.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x