Python Tutorials - Herong's Tutorial Examples - v2.15, by Herong Yang
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
Variables, Operations and Expressions
Function Statement and Function Call
Iterable Objects of Built-in Data Types
►What Is Filtered Generator Expression
What Is Double-Generator Expression
List, Set and Dictionary Comprehensions
Packages and Package Directories
"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