Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate40 min
filter keeps True drops False

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 to list or tuple
  • 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.

filter keeps True values 10 20 40 and drops -30

Syntax: filter(FunctionName, iterable)

Execution flow

filter() processes one element at a time until the iterable is exhausted.

filter takes one value, runs the callback, then keeps or drops
  1. Read one value.
  2. Pass it to the callback.
  3. Keep it only if the result is True.
  4. Continue until all values are checked.
  5. varname is a filter object — cast it to see values.
text
varname = filter(FunctionName, Iterable-object)

Three ways to use filter()

The lesson demonstrates three equivalent styles: normal function, named lambda, and inline lambda.

three filter styles def 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

python
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):

python
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:

python
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.

filter object must be cast with list or tuple to see values
  • list() → list output
  • tuple() → tuple output

Positive and negative filtering

The callback determines which values belong in the final collection. Notice that 0 is excluded from both groups.

positive values kept, negatives kept separately, zero dropped

Why is 0 removed?

  • 0 > 0 → False
  • 0 < 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.

level civic and radar kept, python dropped as not a palindrome

Condition: word == word[::-1]

  • word[::-1] reverses the string
  • Compare original and reversed values
python
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.

hi and AI dropped, tree cat code plus kept by length and isalpha

Conditions:

  • word.isalpha()
  • 3 <= len(word) <= 4

FilterFunsEx5 splits on commas, then keeps tokens that are alphabetic and length 3–4:

python
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.

iterable to callback to boolean to list or tuple collection

Common mistakes

  • Expecting 0 in 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

  1. Add a third filter for zeros only (val == 0).
  2. Change palindromes to case-insensitive (word.lower()).
  3. 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