Python Intermediate and Advanced

Python Intermediate_003: Filter Function

codeaddict 2024. 12. 23. 20:39

003_Python Advanced: Filter Function

What is the filter() Function?

The filter() function in Python is used to filter elements from an iterable (like a list, tuple, etc.) based on a condition provided by a function. It returns a filter object, which is an iterator containing elements that satisfy the condition.

The power of filter() lies in its ability to simplify the process of filtering data without the need for explicit loops.


Syntax of the filter() Function

filter(function, iterable)
  • function: A function that returns True or False for each element in the iterable.
  • iterable: The sequence (e.g., list, tuple, or string) whose elements you want to filter.

If the function returns True, the corresponding element is included in the output.


Example 1: Simple Example

Let’s filter even numbers from a list.

Using a for loop:

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

# Using a for loop to filter even numbers
even_numbers = []
for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)

print(even_numbers)  # Output: [2, 4, 6, 8]

Using filter():

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

# Using filter with a lambda function
even_numbers = filter(lambda x: x % 2 == 0, numbers)

# Convert the filter object to a list
print(list(even_numbers))  # Output: [2, 4, 6, 8]

Example 2: Intermediate Example (Filtering Words by Length)

Let’s filter words that have four or fewer characters.

Using a for loop:

words = ["apple", "kiwi", "banana", "cherry", "fig"]

# Using a for loop to filter short words
short_words = []
for word in words:
    if len(word) <= 4:
        short_words.append(word)

print(short_words)  # Output: ['kiwi', 'fig']

Using filter():

words = ["apple", "kiwi", "banana", "cherry", "fig"]

# Using filter with a lambda function
short_words = filter(lambda word: len(word) <= 4, words)

# Convert the filter object to a list
print(list(short_words))  # Output: ['kiwi', 'fig']

Example 3: Advanced Example (Filtering Dictionaries)

Let’s filter students who passed based on their scores.

Using a for loop:

students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 72},
    {"name": "Charlie", "score": 90},
    {"name": "Daisy", "score": 65},
]

# Using a for loop to filter passed students
passed_students = []
for student in students:
    if student["score"] >= 75:
        passed_students.append(student)

print(passed_students)
# Output: [{'name': 'Alice', 'score': 85}, {'name': 'Charlie', 'score': 90}]

Using filter():

students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 72},
    {"name": "Charlie", "score": 90},
    {"name": "Daisy", "score": 65},
]

# Using filter with a lambda function
passed_students = filter(lambda student: student["score"] >= 75, students)

# Convert the filter object to a list
print(list(passed_students))
# Output: [{'name': 'Alice', 'score': 85}, {'name': 'Charlie', 'score': 90}]

Key Takeaways

  • filter() simplifies data filtering by replacing verbose loops.
  • It works with any iterable and a function returning True or False.
  • Remember to convert the filter object (iterator) to a list, tuple, or other iterable for viewing.

Mastering filter() can make your Python code cleaner and more efficient!