Lesson 03
Python filter() Deep Dive — Keep Values that Return True
Build filter() three ways: a def predicate, a named lambda, and an inline lambda. Extract positives, palindromes, and 3-to-4 letter words.
What you will learn
- The syntax
varname = filter(FunctionName, iterable) - Why FunctionName must return True or False
- Three styles from the teaching files:
def, named lambda, inline lambda - Why you cast a
<class 'filter'>object tolistortuple - Palindrome words and words whose length is 3 or 4 (and alphabetic)
Functions already showed even numbers with filter. This lesson is the FILTER FUNCTIONS folder: positives/negatives, 0 dropped, palindromes, and isalpha() with a length range.
What is filter()?
filter() selects only the elements for which a callback function returns True. Elements returning False are removed.
Syntax: filter(FunctionName, iterable)
Execution flow
filter() processes one element at a time until the iterable is exhausted.
- Read one value.
- Pass it to the callback.
- Keep it only if the result is
True. - Continue until all values are checked.
varnameis a filter object — cast it to see values.
varname = filter(FunctionName, Iterable-object)Three ways to use filter()
The lesson demonstrates three equivalent styles: normal function, named lambda, and inline lambda.
| Style | Best use |
|---|---|
Normal def |
Complex reusable logic |
| Named lambda | Short reusable callback |
| Inline lambda | One-time filtering |
Style 1 — normal functions
def positive(val):
if val > 0:
return True
else:
return False
def negative(val):
return True if val < 0 else False
lst = [10, 20, -30, 40, -67, 23, -7, 0, 12]
filterobj1 = filter(positive, lst)
filterobj2 = filter(negative, lst)
print(type(filterobj1)) # <class 'filter'>
pslist = list(filterobj1)
nglist = tuple(filterobj2)Displaying filterobj1 itself prints a memory address, not [10, 20, 40, ...].
Styles 2 and 3 — lambda
Named lambdas (FilterFunsEx2):
positive = lambda val: True if val > 0 else False
negative = lambda val: True if val < 0 else False
pslist = list(filter(positive, lst))
nglist = tuple(filter(negative, lst))Inline (FilterFunsEx3) — instant operations, no leftover names:
pslist = list(filter(lambda val: True if val > 0 else False, lst))
nglist = tuple(filter(lambda val: True if val < 0 else False, lst))Classroom demos read input().split(). Here lst is a literal so the playground can run.
Why cast to list() or tuple()?
filter() does not immediately return a list. It returns a filter object, so you must cast it to view the values.
list()→ list outputtuple()→ tuple output
Positive and negative filtering
The callback determines which values belong in the final collection. Notice that 0 is excluded from both groups.
Why is 0 removed?
0 > 0→ False0 < 0→ False
Zero is neither positive nor negative, so it disappears from both the positive list and the negative tuple.
Palindrome filter
filter() can also work with strings. The lesson keeps only words that read the same forwards and backwards.
Condition: word == word[::-1]
word[::-1]reverses the string- Compare original and reversed values
words = "level python civic radar hello".split()
palwords = list(filter(lambda word: word == word[::-1], words))
# ['level', 'civic', 'radar']The callback does not need True if ... else False when the expression is already a boolean.
Filter words of length 3–4
The module combines two conditions: the word must contain only letters and its length must be between 3 and 4.
Conditions:
word.isalpha()3 <= len(word) <= 4
FilterFunsEx5 splits on commas, then keeps tokens that are alphabetic and length 3–4:
tokens = [w.strip() for w in "hi,tree,cat,code,I,book,sun,AI,plus".split(",")]
words34 = list(filter(lambda word: word.isalpha() and 3 <= len(word) <= 4, tokens))
# hi (2) dropped, I dropped, AI (2) dropped, tree (4) kept, cat kept, ...word.isalpha() rejects digits and punctuation. 3 <= len(word) <= 4 is a chained comparison.
Complete filter() pipeline
Every filter() program follows the same processing pipeline shown in the lesson.
Common mistakes
- Expecting
0in the positive list because it is “not negative” - Printing the filter object without
list()/tuple() - Using a callback that returns a number instead of a predicate (non-zero is truthy, but the notes teach True/False)
- Forgetting
isalpha()when the CSV mix includes symbols
Interview cheat sheet
| Question | Answer |
|---|---|
| Purpose | Keep elements matching a condition |
| First parameter | Callback function |
| Return type | Filter object |
| View values | Cast using list() or tuple() |
| Key rule | Keep only values returning True |
| Zero vs sign | 0 > 0 is False, 0 < 0 is False |
| Palindrome test | word == word[::-1] |
Practice in the playground
- Add a third filter for zeros only (
val == 0). - Change palindromes to case-insensitive (
word.lower()). - Raise the length filter to
4 <= len(word) <= 5.
Next: map() and zip().
Loading playground…
Check your understanding
filter() quiz
What is the teaching-notes syntax for filter?
1 / 10