← Python lessons

Python Generator Function: Filter Lines with yield

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A Python generator function can filter data. It loops over the items it is given and reaches yield only for the items that pass a test.

You will write filters that take any iterable as a parameter. Prerequisites: if statements, string methods and Python yield vs return. No imports are needed.

Yield only the items that pass a test

Put the yield inside an if. Items that fail the test are skipped.

def long_words(words):    for word in words:        if len(word) > 4:            yield wordfor word in long_words(["kiwi", "banana", "fig", "cherry"]):    print(word)

This prints banana and cherry. The generator still looks at every word, but it hands over only two.

Test the start of a string with startswith()

text.startswith(prefix) is True when the text begins with that prefix. It is a useful test for lines of text.

code = ["# set up", "total = 0", "total += 5  # add", "# finished"]for line in code:    print(line.startswith("#"), "#" in line)

This prints True True, False False, False True, True True. The third line has a # in the middle, so it does not start with one. A filter that tested "#" in line would keep it.

A filter accepts any iterable

The parameter does not have to be a list. A range, a file or another generator works too.

def multiples_of_three(numbers):    for number in numbers:        if number % 3 == 0:            yield numberprint(list(multiples_of_three(range(1, 13))))print(list(multiples_of_three([5, 7, 8])))

This prints [3, 6, 9, 12], then []. When nothing passes the test, the generator ends without yielding. That is not an error.

Choose a generator function or a generator expression

A short filter also fits in a generator expression: (word for word in words if len(word) > 4). Write a generator function when the filter needs a name, a parameter, or more than one statement.

Note: A filter never changes its input. The original list still holds every item.

See also: Python Generator Expressions Explained, String methods.

Your turn

Write the generator passing(scores). It yields only the scores that are 50 or more. The loop is supplied.

🎯 Goal — make it print exactly:
72
50
95
# Define passing(scores) here.for score in passing([72, 41, 50, 38, 95]):    print(score)