ZetCode

Python predicate

last modified November 17, 2026 Python 3.15

In this article we explain predicates in Python and show how to use them with built-in functions, comprehensions, and the standard library.

A predicate is, in general meaning, a statement about something that is either true or false. In programming, a predicate is a function that takes one argument and returns a boolean value. Predicates express conditions such as is positive, is a vowel, or is an active user.

Many Python functions accept a predicate as an argument: filter, itertools.takewhile, itertools.dropwhile, and itertools.filterfalse are examples. The function calls the predicate for each element and decides what to do with the element based on the result. Predicates are also used in the if clause of comprehensions and generator expressions and together with any and all.

Python does not require a predicate to return exactly True or False; any value is interpreted by its truthiness. Empty strings and collections, zero, and None are false, everything else is true.

Simple predicate

The following is a simple example using a predicate function.

positive.py
def is_positive(n):
    return n > 0


vals = [-3, 2, 7, 9, -1, 0, 2, 3, 1, -4, 6]

res = filter(is_positive, vals)
print(list(res))

We have a list of integers. With the filter function and a predicate, we pick the positive values.

def is_positive(n):
    return n > 0

The is_positive function is a predicate. It returns True for all values that are greater than zero. A common convention is to start predicate names with is_ or has_.

res = filter(is_positive, vals)

The filter function takes the predicate as its first argument. We pass the function itself, not the result of a call, so there are no parentheses after is_positive. The filter function returns a lazy iterator of the elements for which the predicate is true.

print(list(res))

We turn the iterator into a list with the list built-in function.

$ python positive.py
[2, 7, 9, 2, 3, 1, 6]

Anonymous predicate

Short predicates that are used only once are often written as lambda expressions.

negative.py
vals = [-3, 2, 7, 9, -1, 0, 2, 3, 1, -4, 6]

res = filter(lambda e: e < 0, vals)
print(list(res))

In the example, we filter out all elements that are negative with an anonymous predicate. The lambda e: e < 0 expression creates a function that returns True for negative numbers.

$ python negative.py
[-3, -1, -4]

Predicate in a list comprehension

A predicate can be used in the if clause of a list comprehension. Comprehensions are often preferred to filter, since they can transform the elements in the same expression.

vowels.py
def is_vowel(c):
    return c.lower() in 'aeiou'


sentence = 'An eagle is flying in the sky.'

vowels = [c for c in sentence if is_vowel(c)]
print(vowels)

consonants = [c for c in sentence if c.isalpha() and not is_vowel(c)]
print(consonants)

The example picks vowels and consonants from a sentence.

def is_vowel(c):
    return c.lower() in 'aeiou'

The is_vowel predicate returns True for a vowel character. The in operator already produces a boolean, so there is no need for an if/else statement that returns True or False explicitly. The lower call makes the check case-insensitive.

vowels = [c for c in sentence if is_vowel(c)]

The logic of the if condition is delegated to the is_vowel predicate.

consonants = [c for c in sentence if c.isalpha() and not is_vowel(c)]

Predicates can be combined with the and, or, and not operators. A consonant is a letter that is not a vowel; the isalpha call skips spaces and the dot.

$ python vowels.py
['A', 'e', 'a', 'e', 'i', 'i', 'i', 'e']
['n', 'g', 'l', 's', 'f', 'l', 'y', 'n', 'g', 'n', 't', 'h', 's', 'k', 'y']

Built-in predicates

We do not always have to write our own predicates. Many built-in functions and methods are predicates: callable, str.isdigit, str.isupper, os.path.isdir, and others. Passing None instead of a function to filter keeps the truthy elements.

builtin_preds.py
import os

vals = ['12', 'sky', '7', '', 'BLUE', '3.4', 'Falcon', None, '0']

print(list(filter(None, vals)))

words = [e for e in vals if e]
print(list(filter(str.isdigit, words)))
print(list(filter(str.isupper, words)))
print(list(filter(str.istitle, words)))

objects = [len, 'len', print, 42, str.upper]
print(list(filter(callable, objects)))

print(list(filter(os.path.isdir, ['/etc', '/etc/hostname', '/tmp'])))

The example filters a list with several ready-made predicates.

print(list(filter(None, vals)))

With None, filter uses the elements themselves as conditions. The empty string and None are removed; the '0' string stays, because it is a non-empty string.

print(list(filter(str.isdigit, words)))

The str.isdigit unbound method is called with each string as its argument. Note that '3.4' is not accepted, because the dot is not a digit.

print(list(filter(callable, objects)))

The callable built-in tells whether an object can be called. Functions and methods pass, a string and an integer do not.

print(list(filter(os.path.isdir, ['/etc', '/etc/hostname', '/tmp'])))

The os.path.isdir predicate checks the file system; we keep only the paths that are directories.

$ python builtin_preds.py
['12', 'sky', '7', 'BLUE', '3.4', 'Falcon', '0']
['12', '7', '0']
['BLUE']
['Falcon']
[<built-in function len>, <built-in function print>, <method 'upper' of 'str' objects>]
['/etc', '/tmp']

Predicates with any and all

The any function returns True if the predicate holds for at least one element, and all returns True if it holds for every element. Both functions short-circuit: they stop as soon as the result is known.

any_all.py
def is_even(n):
    return n % 2 == 0


vals = [2, 4, 6, 8, 10, 13]

print(all(is_even(e) for e in vals))
print(any(is_even(e) for e in vals))
print(any(e > 20 for e in vals))

print(all(e > 0 for e in []))
print(any(e > 0 for e in []))

We pass generator expressions that apply the predicates to the elements.

print(all(is_even(e) for e in vals))
print(any(is_even(e) for e in vals))

Not all values are even, because 13 is odd; but at least one value is.

print(all(e > 0 for e in []))
print(any(e > 0 for e in []))

For an empty iterable, all returns True and any returns False. There is no element that would violate the condition, and there is no element that would satisfy it.

$ python any_all.py
False
True
False
True
False

Counting and finding with predicates

Since True equals 1 and False equals 0, we can count matching elements by summing the predicate results. The first matching element can be found with next.

count_first.py
words = ['sky', 'forest', 'war', 'cloud', 'water', 'rock', 'wood', 'cup']

def starts_with_w(word):
    return word.startswith('w')


n = sum(starts_with_w(w) for w in words)
print(f'{n} words start with w')

first = next(filter(starts_with_w, words), None)
print(f'first word starting with w: {first}')

first = next((w for w in words if len(w) > 10), None)
print(f'first word longer than ten: {first}')

idx = [i for i, w in enumerate(words) if starts_with_w(w)]
print(f'indexes: {idx}')

The example counts words that start with the letter w, finds the first such word, and lists their indexes.

n = sum(starts_with_w(w) for w in words)

The sum function adds up the booleans returned by the predicate.

first = next(filter(starts_with_w, words), None)

The next function takes the first element from the lazy iterator; the iterator does not examine the rest of the list. The second argument is a default that is returned when no element matches; without it, next raises StopIteration.

idx = [i for i, w in enumerate(words) if starts_with_w(w)]

With enumerate, we get the positions of the matching elements.

$ python count_first.py
3 words start with w
first word starting with w: war
first word longer than ten: None
indexes: [2, 4, 6]

The itertools module

The itertools module contains several functions driven by predicates. The takewhile function returns elements while the predicate is true, dropwhile skips elements while the predicate is true and returns the rest, and filterfalse is the opposite of filter.

take_drop.py
from itertools import dropwhile, filterfalse, takewhile

temps = [3, 5, 8, 12, 15, 11, 7, 4, 13, 2]

def is_cold(t):
    return t < 10


print(list(takewhile(is_cold, temps)))
print(list(dropwhile(is_cold, temps)))
print(list(filter(is_cold, temps)))
print(list(filterfalse(is_cold, temps)))

We have a list of temperatures. The is_cold predicate returns True for temperatures below ten degrees.

print(list(takewhile(is_cold, temps)))
print(list(dropwhile(is_cold, temps)))

Unlike filter, these two functions look only at the beginning of the sequence. The takewhile function stops at the first warm temperature, 12, and dropwhile returns everything from that point on, including the cold values that come later.

print(list(filter(is_cold, temps)))
print(list(filterfalse(is_cold, temps)))

The filter and filterfalse functions examine every element and split the list into the cold and warm temperatures.

$ python take_drop.py
[3, 5, 8]
[12, 15, 11, 7, 4, 13, 2]
[3, 5, 8, 7, 4, 2]
[12, 15, 11, 13]

Predicates from operator and partial

Instead of writing small functions or lambdas, we can build predicates from the functions of the operator module. The functools.partial function fixes the first argument of a two-argument function, which gives us a one-argument predicate.

partial_pred.py
from functools import partial
from operator import contains, gt, itemgetter, lt, methodcaller

vals = [-3, 2, 7, 9, -1, 0, 2, 3, 1, -4, 6]

is_positive = partial(lt, 0)
print(is_positive(5), is_positive(-5))

is_negative = partial(gt, 0)
print(list(filter(is_negative, vals)))

is_vowel = partial(contains, 'aeiou')
print(list(filter(is_vowel, 'an old falcon')))

ends_with_s = methodcaller('endswith', 's')
print(list(filter(ends_with_s, ['cups', 'pen', 'books', 'tree'])))

users = [('John', True), ('Lucy', False), ('Paul', True)]
is_active = itemgetter(1)
print([name for name, _ in filter(is_active, users)])

The example creates predicates without the def or lambda keywords.

is_positive = partial(lt, 0)

The partial(lt, 0) call creates a function that calls lt(0, x), which is 0 < x. We must be careful about the order of the arguments: partial(gt, 0) means 0 > x and is therefore a predicate for negative numbers.

is_vowel = partial(contains, 'aeiou')

The contains(a, b) function is the same as b in a.

ends_with_s = methodcaller('endswith', 's')

The methodcaller function creates a callable that calls the endswith method with the 's' argument on the object it receives.

is_active = itemgetter(1)

The itemgetter(1) callable returns the second element of a tuple. Here the element is a boolean flag, so the item getter works as a predicate.

$ python partial_pred.py
True False
[-3, -1, -4]
['a', 'o', 'a', 'o']
['cups', 'books']
['John', 'Paul']

Combining predicates

Since functions are first-class objects in Python, we can write higher-order functions that take predicates and return new predicates.

combine.py
def negate(pred):
    return lambda x: not pred(x)


def all_of(*preds):
    return lambda x: all(p(x) for p in preds)


def any_of(*preds):
    return lambda x: any(p(x) for p in preds)


def is_even(n):
    return n % 2 == 0


def is_positive(n):
    return n > 0


def is_big(n):
    return abs(n) > 100


vals = [-120, -7, -4, 0, 3, 8, 12, 99, 250, 301]

print(list(filter(negate(is_even), vals)))
print(list(filter(all_of(is_even, is_positive), vals)))
print(list(filter(any_of(is_big, negate(is_positive)), vals)))

We define three combinators: negate, all_of, and any_of.

def negate(pred):
    return lambda x: not pred(x)

The negate function returns a predicate with the opposite result.

def all_of(*preds):
    return lambda x: all(p(x) for p in preds)

The all_of function returns a predicate that is true only if all the given predicates are true for the value.

print(list(filter(any_of(is_big, negate(is_positive)), vals)))

Combinators can be nested. This predicate accepts values whose absolute value is greater than 100 or which are not positive.

$ python combine.py
[-7, 3, 99, 301]
[8, 12, 250]
[-120, -7, -4, 0, 250, 301]

Predicates with more_itertools

The third-party more_itertools library contains plenty of functions for working with iterables; many of them accept predicates.

$ pip install more-itertools

The locate, partition, first_true, and quantify functions

We use four of the predicate-driven functions from the library.

more_iter.py
from more_itertools import first_true, locate, partition, quantify

vals = [-3, 2, 7, 9, -1, 0, 2, 3, 1, -4, 6]

def is_even_positive(n):
    return n > 0 and n % 2 == 0


idx = list(locate(vals, is_even_positive))
print(idx)
print([vals[i] for i in idx])

odd, even = partition(lambda n: n % 2 == 0, vals)
print(list(odd), list(even))

print(first_true(vals, pred=lambda n: n > 5))
print(first_true(vals, default=-1, pred=lambda n: n > 50))

print(quantify(vals, is_even_positive))

The is_even_positive predicate accepts values that are greater than zero and divisible by two.

idx = list(locate(vals, is_even_positive))
print(idx)
print([vals[i] for i in idx])

The locate function returns the indexes of the elements that satisfy the predicate. We turn the indexes into values with a list comprehension.

odd, even = partition(lambda n: n % 2 == 0, vals)

The partition function splits the elements into two iterators: the first contains the elements for which the predicate is false, the second those for which it is true. Note that the predicate comes first here.

print(first_true(vals, pred=lambda n: n > 5))
print(first_true(vals, default=-1, pred=lambda n: n > 50))

The first_true function returns the first element that satisfies the predicate, or the default value if there is no such element.

print(quantify(vals, is_even_positive))

The quantify function counts how many times the predicate is true.

$ python more_iter.py
[1, 6, 10]
[2, 2, 6]
[-3, 7, 9, -1, 3, 1] [2, 0, 2, -4, 6]
7
-1
3

Type predicates with TypeIs

A type checker does not know what a predicate tests. If a predicate checks the type of its argument, we can annotate its return value with typing.TypeIs (Python 3.13). Type checkers then narrow the type of the argument in the if and else branches.

typeis_pred.py
from typing import TypeIs


def is_str(val: object) -> TypeIs[str]:
    return isinstance(val, str)


def describe(val: int | str) -> str:
    if is_str(val):
        return val.upper()
    else:
        return f'{val:,}'


print(describe('falcon'))
print(describe(12_000_000))

The is_str predicate returns TypeIs[str].

if is_str(val):
    return val.upper()
else:
    return f'{val:,}'

In the if branch, the type checker treats val as a str; in the else branch as an int. At runtime, TypeIs has no effect; the predicate returns an ordinary boolean.

The typeis_bad.py file contains the same code, but the is_str predicate is annotated to return a plain bool. We check both files with mypy; the version without TypeIs is rejected, because mypy cannot tell that val is a string in the if branch.

$ python typeis_pred.py
FALCON
12,000,000
$ mypy typeis_pred.py
Success: no issues found in 1 source file
$ mypy typeis_bad.py
typeis_bad.py:7: error: Item "int" of "int | str" has no attribute "upper"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Source

Functional Programming HOWTO

itertools — Functions creating iterators for efficient looping

typing.TypeIs

more-itertools documentation

In this article we have worked with predicates in Python. See also Python filter list, Python lambda, Python any and all, Python itertools, and Python operator module.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.