liveBook · Manning

Guard

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A guard is a conditional clause in a comprehension that determines which iterated elements are included in the resulting collection.

A guard statement is the if condition in a list comprehension. It keeps only iterated elements whose condition evaluates as truthy, producing a filtered collection. section 14.3.1

Keep consonants

vowels = 'aeiou' consonants = ''.join([c for c in string.ascii_lowercase if c not in vowels]) The guard excludes vowels and retains consonants. The same selection can be written with filter(), which applies a function to each iterable element. section 14.3.1

>>> cars = ['blue Honda', 'red Chevy', 'blue Ford']
>>> list(filter(lambda car: car.startswith('blue '), cars))
['blue Honda', 'blue Ford']

Compare guard-based selection with filtering cars by a string prefix; rejected elements simply disappear from the resulting list. section 14.3.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines truthy inclusion, demonstrates comprehensions and filter(), and shows empty results without examining interpreter internals.
Examples
Demonstrates consonant extraction, blue-car selection, numbers greater than ten, and rhyming-prefix exclusion.
What it assumes
Builds on iterables and list comprehensions while teaching Boolean truthiness through filtering examples.
What you can do after
Apply it via list comprehensions or filter() to build collections containing only elements that satisfy a condition.
How it connects
Connects list comprehensions with filter(), higher-order functions, iterables, lambda expressions, and truthiness.

Also explained in

Compare how 4 books explain guard →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.