Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Filter in Python
The filter() function in Python creates a new iterator from elements of an iterable for which a function returns True. It's useful for extracting elements that meet specific criteria from lists, tuples, or other sequences.
Syntax
filter(function, iterable)
Parameters:
-
function − A function that returns
TrueorFalsefor each element - iterable − Any sequence like list, tuple, set, or string to be filtered
Basic Example
Let's filter months that have 30 days from a list of months ?
# List of months
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug']
# Function that checks if month has 30 days
def has_30_days(month):
months_with_30 = ['Apr', 'Jun', 'Sep', 'Nov']
return month in months_with_30
# Filter months with 30 days
filtered_months = filter(has_30_days, months)
print('Months with 30 days:')
for month in filtered_months:
print(month)
Months with 30 days: Apr Jun
Using Lambda Functions
You can use lambda functions for simple filtering conditions ?
# Filter even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print("Even numbers:", list(even_numbers))
# Filter strings longer than 3 characters
words = ['cat', 'dog', 'elephant', 'rat', 'tiger']
long_words = filter(lambda word: len(word) > 3, words)
print("Long words:", list(long_words))
Even numbers: [2, 4, 6, 8, 10] Long words: ['elephant', 'tiger']
Filter with None
When you pass None as the function, filter() removes falsy values ?
# Remove falsy values (0, '', None, False, empty lists)
mixed_data = [1, 0, 'hello', '', None, 42, False, [], 'world']
# Filter out falsy values
truthy_values = filter(None, mixed_data)
print("Truthy values:", list(truthy_values))
Truthy values: [1, 'hello', 42, 'world']
Comparison with List Comprehension
| Method | Syntax | Returns | Memory Usage |
|---|---|---|---|
filter() |
filter(func, iterable) |
Iterator | Low (lazy evaluation) |
| List Comprehension | [x for x in iterable if condition] |
List | Higher (creates list immediately) |
Practical Example
Here's how to filter student records based on grades ?
# Student data
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 72},
{'name': 'Charlie', 'grade': 91},
{'name': 'Diana', 'grade': 68}
]
# Filter students with grades above 75
def passed_exam(student):
return student['grade'] > 75
passed_students = filter(passed_exam, students)
print("Students who passed:")
for student in passed_students:
print(f"{student['name']}: {student['grade']}")
Students who passed: Alice: 85 Charlie: 91
Conclusion
The filter() function provides an efficient way to extract elements that meet specific criteria from iterables. Use it with lambda functions for simple conditions or regular functions for complex filtering logic.
Advertisements
