- Aliases
- and operator
- Arrays
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Filter()
- Floats
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- OOP
- or operator
- Parameters
- print() function
- Property()
- Random module
- range() function
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
- Zip function
PYTHON
Python filter()
: Syntax, Usage, and Examples
You can use the filter()
function in Python to extract elements from a sequence that meet a certain condition. Instead of writing a full loop with if
statements, the Python filter()
function lets you express filtering logic in a clear and concise way. It returns only those values for which a given function returns True
.
This function comes in handy when you're working with lists, arrays, or dictionaries and want to clean up or reduce data without mutating the original structure.
How filter()
Works in Python
The basic syntax is:
filter(function, iterable)
function
: A callable that accepts one argument and returnsTrue
orFalse
.iterable
: Any iterable object like a list, tuple, set, or dictionary.
The result is a filter object—an iterator—which you can convert to a list or another iterable if needed.
Example
def is_positive(num):
return num > 0
numbers = [-3, -1, 0, 2, 5]
filtered = filter(is_positive, numbers)
print(list(filtered)) # Output: [2, 5]
You can also use a lambda function instead of defining a named one:
print(list(filter(lambda x: x > 0, numbers)))
Why Use filter()
in Python
You should reach for filter()
when you want to streamline conditional selection. It's especially useful for:
- Keeping only valid data entries from a list or array
- Applying business rules to datasets
- Filtering user input or API responses
- Simplifying logic in functional pipelines
Instead of managing temporary lists and for
loops manually, you express your filtering logic in one line.
Practical Examples
Remove Empty Strings from a List
values = ["apple", "", "banana", "", "cherry"]
cleaned = list(filter(None, values))
print(cleaned) # Output: ['apple', 'banana', 'cherry']
Passing None
as the function filters out all falsy values, including ""
, 0
, False
, and None
.
Filter a List with a Condition
ages = [12, 17, 21, 30, 15]
adults = list(filter(lambda age: age >= 18, ages))
print(adults) # Output: [21, 30]
This example reads almost like plain English: keep only the ages that are 18 or older.
Filter a Dictionary by Value
scores = {"Alice": 85, "Bob": 42, "Cleo": 91}
passed = dict(filter(lambda item: item[1] >= 60, scores.items()))
print(passed) # Output: {'Alice': 85, 'Cleo': 91}
Using filter()
with .items()
makes it easy to work with dictionaries.
Filter Custom Objects
class Task:
def __init__(self, title, done):
self.title = title
self.done = done
tasks = [
Task("Write report", True),
Task("Test code", False),
Task("Send email", True)
]
completed = list(filter(lambda task: task.done, tasks))
for task in completed:
print(task.title) # Output: Write report, Send email
This pattern works great for task managers or any object-based application.
Combining filter()
with Other Tools
Use map()
and filter()
Together
You can pair filtering and transformation in a single pipeline:
numbers = [1, 2, 3, 4, 5, 6]
squares_of_even = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)))
print(squares_of_even) # Output: [4, 16, 36]
First, the list gets filtered, then each remaining item is squared.
List Comprehension vs. filter()
You can achieve the same result with list comprehension:
[x for x in numbers if x % 2 == 0]
Use filter()
when the function is reusable or comes from another part of your program. Prefer comprehensions for simpler, more inline logic.
Filtering in Common Scenarios
Filter Input Data
raw_input = ["", "email@example.com", None, "admin@site.com"]
valid = list(filter(lambda x: x, raw_input))
This quickly removes blanks or null entries before saving or processing.
Filter from External Sources
When parsing data from APIs or user uploads, filter()
gives you an easy first-pass cleanup:
records = [{"id": 1}, {}, {"id": 2}]
valid_records = list(filter(lambda r: "id" in r, records))
This ensures only entries with required fields stay in the list.
Create Your Own Filtering Function
def is_uppercase(word):
return word.isupper()
words = ["YES", "no", "MAYBE", "sure"]
result = list(filter(is_uppercase, words))
You can apply any condition you want, as long as your function returns a boolean.
Considerations When Using filter()
in Python
filter()
returns an iterator. If you need to reuse the results, convert it to a list right away.- Avoid overusing it for complex logic. If your condition spans more than one line, use a regular
for
loop instead. - Don’t mix filtering and side effects. Keep your filtering functions pure—no printing, writing to files, or modifying global variables.
Related Use Cases
Filtering Arrays (Python Array Filter)
You can use filter()
on arrays created from the array
module:
import array
data = array.array("i", [1, -2, 3, -4])
positives = list(filter(lambda x: x > 0, data))
Works just like with lists, as long as the iterable is compatible.
Filtering with lambda
(Lambda Python Filter)
Using lambda
functions is a common way to define one-off filters inline. Just make sure your lambda stays readable. For anything complex, break it into a named function.
Filtering in Data Analysis
While Python’s built-in filter()
is useful, libraries like pandas
offer even more powerful filtering options. Still, mastering the core filter()
function helps you build solid foundations before moving to more advanced tools.
The Python filter()
function gives you a clean, expressive way to extract specific data from any iterable. By using it effectively, you can write code that reads well, performs reliably, and handles common data-processing patterns with ease. When paired with functions, lambdas, or tools like map()
, it becomes a key part of your Python programming toolbox.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.