- Learning Objectives
- Prerequisites
- Introduction
- What is filter()?
- Why is filter() Required?
- Syntax
- Parameters
- Return Value
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand the purpose of the filter() function.
- Filter iterable objects based on conditions.
- Use filter() with normal functions.
- Use filter() with lambda functions.
- Convert filter objects into lists, tuples, and sets.
- Apply filter() in real-world applications.
Before learning this chapter, you should know:
- Functions
- Lambda Functions
- Lists
- Conditional Statements
- map() Function
In Python,
there are situations where we need only specific elements from a collection.
For example,
- Select only even numbers.
- Select only positive numbers.
- Select students who passed.
- Select names starting with a specific letter.
Instead of writing loops,
Python provides the
filter()function.
The filter() function filters elements from an iterable based on a condition and returns only those elements that satisfy the condition.
filter()selects only the elements that satisfy a given condition.
Suppose we have
[10, 15, 20, 25, 30]
If we need only even numbers,
instead of writing loops,
we use
filter()filter(function, iterable)A function that returns either
Trueor
FalseIt can be
- Normal Function
- Lambda Function
Any iterable object such as
- List
- Tuple
- Set
- Dictionary
- String
Returns a
filter objectwhich can be converted into
- list
- tuple
- set
Example
numbers = [10,15,20,25]
result = filter(lambda x: x % 2 == 0, numbers)Execution
10 → True
15 → False
20 → True
25 → False
Result
10
20
| map() | filter() |
|---|---|
| Transforms every element | Selects specific elements |
| Output size is generally the same as input | Output size may be smaller |
| Returns modified values | Returns original values that satisfy the condition |
Iterable
↓
filter()
↓
Condition Checked
↓
True ?
↓
Yes
↓
Keep Element
↓
No
↓
Discard Element
↓
Filter Object
↓
list()
↓
Output
- Less code.
- Easy filtering.
- Improves readability.
- Works well with lambda.
- Useful for data processing.
- Keep filtering conditions simple.
- Use lambda only for short conditions.
- Use normal functions for complex logic.
- Convert filter objects into lists when required.
- Choose meaningful variable names.
Printing a filter object directly.
Incorrect
result = filter(lambda x:x>10,[1,2,3])
print(result)Correct
print(list(result))Returning values other than Boolean.
Although Python evaluates truthy and falsy values, writing conditions that clearly return True or False makes the code easier to understand.
Using filter() when map() is required.
Remember
- map() → modifies values
- filter() → selects values
numbers = [1,2,3,4,5,6,7,8]
result = filter(lambda x:x%2==0,numbers)
print(list(result))[2, 4, 6, 8]
numbers = [1,2,3,4,5,6]
result = filter(lambda x:x%2!=0,numbers)
print(list(result))[1, 3, 5]
numbers = [-5,-2,0,4,8,-1]
result = filter(lambda x:x>0,numbers)
print(list(result))[4, 8]
numbers = [-8,5,-4,7,-1]
result = filter(lambda x:x<0,numbers)
print(list(result))[-8, -4, -1]
numbers = [20,55,80,35,90]
result = filter(lambda x:x>50,numbers)
print(list(result))[55, 80, 90]
marks = [35,80,65,20,90,40]
result = filter(lambda x:x>=35,marks)
print(list(result))[35, 80, 65, 90, 40]
names = ["Java","Python","C","Oracle"]
result = filter(lambda x:len(x)>4,names)
print(list(result))['Python', 'Oracle']
names = ["Amit","Rahul","Anil","Kiran"]
result = filter(lambda x:x.startswith("A"),names)
print(list(result))['Amit', 'Anil']
def even(number):
return number%2==0
numbers=[10,15,20,25,30]
result=filter(even,numbers)
print(list(result))[10, 20, 30]
names=["Python","","Java","","SQL"]
result=filter(None,names)
print(list(result))['Python', 'Java', 'SQL']
List
↓
filter()
↓
Condition Checked
↓
True ?
↓
Keep Element
↓
False ?
↓
Ignore Element
↓
Filter Object
↓
list()
↓
Output
numbers
│
├──10
├──15
├──20
├──25
├──30
↓
filter()
↓
Lambda Function
↓
Filter Object
↓
List
- Efficient filtering.
- Shorter code.
- Better readability.
- Supports lambda functions.
- Useful for data analysis.
- Use simple filtering conditions.
- Prefer lambda for one-line conditions.
- Use normal functions for complex conditions.
- Convert filter objects into lists when necessary.
- Printing filter objects directly.
- Using filter() instead of map().
- Writing overly complex lambda expressions.
- Forgetting that filter() returns original elements, not modified ones.
filter() selects elements from an iterable that satisfy a given condition.
A filter object.
Yes.
Lambda functions are commonly used with filter().
A Boolean value (True or False).
The element is included in the output.
The element is excluded from the output.
map() transforms every element.
filter() selects only the elements that satisfy a condition.
Yes.
It works with both normal functions and lambda functions.
- Find even numbers using filter().
- Find odd numbers.
- Find positive numbers.
- Find students who passed.
- Find names beginning with a specific letter.
filter()→ Selects elements.- Returns a filter object.
- Uses Boolean conditions.
- Works with lambda.
- Convert using
list().
In this chapter, you learned:
- filter() Function
- Syntax
- Parameters
- Return Value
- Lambda with filter()
- Normal Function with filter()
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision