Python filter() Built in Function

The filter() function in Python is used to filter out elements from an iterable (such as a list, tuple, or string) that satisfy a given condition. The filter() function takes two arguments: a function that returns True or False for each element, and an iterable to apply the function to. The filter() function returns a new iterable with only the elements that return True for the function. Here are some examples of using filter() in Python:

Filter a list of numbers to only include even numbers:

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

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers)

Output: [2, 4, 6, 8, 10]

In this example, we use filter() to create a new list called even_numbers that only includes the even numbers from the original list numbers. The lambda function inside the filter() function takes a single argument x and returns True if x is even (x % 2 == 0), and False otherwise. The list() function is used to convert the resulting filter object into a list.

Filter a list of strings to only include those that start with a specific letter:

fruits = ['apple', 'banana', 'cherry', 'durian', 'elderberry']

starts_with_c = list(filter(lambda x: x.startswith('c'), fruits))

print(starts_with_c)

Output: ['cherry']

In this example, we use filter() to create a new list called starts_with_c that only includes the strings from the original list fruits that start with the letter 'c'. The lambda function inside the filter() function takes a single argument x and returns True if x starts with the letter 'c' (x.startswith('c')), and False otherwise.

Filter a list of dictionaries to only include those that meet a certain criteria:

people = [    {'name': 'Alice', 'age': 25},    {'name': 'Bob', 'age': 30},    {'name': 'Charlie', 'age': 35},    {'name': 'Dave', 'age': 40},]

over_30 = list(filter(lambda x: x['age'] > 30, people))

print(over_30)

Output: [{'name': 'Charlie', 'age': 35}, {'name': 'Dave', 'age': 40}]

In this example, we use filter() to create a new list called over_30 that only includes the dictionaries from the original list people where the value associated with the 'age' key is greater than 30. The lambda function inside the filter() function takes a single argument x (which is a dictionary in this case) and returns True if x['age'] is greater than 30, and False otherwise.

Some more examples:

# Filter out odd numbers from a list
numbers = [1, 2, 3, 4, 5, 6]
def is_even(x):
    return x % 2 == 0
# Return True if x is even
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
# Output: [2, 4, 6]


# Filter out vowels from a string
letters = "Hello World"
def is_consonant(x):
    vowels = "aeiouAEIOU"
    return x not in vowels
# Return True if x is not a vowel
consonants = filter(is_consonant, letters)
print("".join(consonants))
# Output: Hll Wrld


# Filter out spam messages from a dataset
import re # Import regex module
messages = ["Hi there!", "You have won $1000!", "Call me ASAP", "Claim your free gift now!"]
def is_spam(x):
    spam_words = ["won", "free", "gift", "claim"]
# List of spam words
    pattern = "|".join(spam_words) # Create a regex pattern with spam words
    return bool(re.search(pattern, x)) # Return True if x matches the pattern
spam_messages = filter(is_spam, messages)
print(list(spam_messages))
# Output: ['You have won $1000!', 'Claim your free gift now!']

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions