What Is Filtered Generator Expression

This section provides a quick introduction of filtered generator expression, which contains a 'for' clause with a 'if' sub-clause enclosed in parentheses and returns a generator iterator.

What Is Filtered Generator Expression - A filtered generator expression is a special expression that contains a "for" clause with an "if" sub-clause enclosed in parentheses and returns a generator iterator.

Here is the syntax of a generator expression:

(EXPRRESSION for VAR in ITERABLE if CONDITION)

The logic of using a filtered generator expression can be described as:

A filtered generator expression can also be viewed as as shortened version of a generator function without name and parameters. So x and y in the following code are equivalent.

def f():
   for VAR in ITERABLE:
      if CONDITION:
         yield EXPRRESSION

x = f()

y = (EXPRRESSION for VAR in ITERABLE if CONDITION)

Here is an example of using a filtered generator expression:

>>> g = (x*x for x in range(1, 11) if x%2==0)
>>> for y in g:
...    print(y)
...
4
16
36
64
100

Table of Contents

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

 Variables, Operations and Expressions

 Statements - Execution Units

 Function Statement and Function Call

Iterators and Generators

 What Is Iterator Object

 What Is Iterable Object

 Iterable Objects of Built-in Data Types

 What Is Generator Iterator

 What Is Generator Expression

What Is Filtered Generator Expression

 What Is Double-Generator Expression

 List, Set and Dictionary Comprehensions

 Classes and Instances

 Modules and Module Files

 Packages and Package Directories

 "sys" and "os" Modules

 "pathlib" - Object-Oriented Filesystem Paths

 "pip" - Package Installer for Python

 SciPy.org - Python Libraries for Science

 pandas - Data Analysis and Manipulation

 Anaconda - Python Environment Manager

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB