What Is Double-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 Double-Generator Expression - A double-generator expression is a generator expression that contains a double "for" clause as shown below:

(EXPRRESSION for VAR_1 in ITERABLE_1 for VAR_2 in ITERABLE_2)

Logically, a double-generator expression is equivalent to the following generator function:

def f():
   for VAR_1 in ITERABLE_1:
      for VAR_2 in ITERABLE_2:
         yield EXPRRESSION

Here is an example of using a double-generator expression:

>>> g = (x*y for x in range(1, 4) for y in range(11, 14))
>>> for z in g:
...    print(z)
...
11
12
13
22
24
26
33
36
39

Of course, a double-generator expression can also be filtered with "if" sub-clauses:

(EXPRRESSION for VAR_1 in ITERABLE_1 if CONDITION_1 \
   for VAR_2 in ITERABLE_2 if CONDITION_2)

Logically, a filtered double-generator expression is equivalent to the following generator function:

def f():
   for VAR_1 in ITERABLE_1:
      if CONDITION_1:
         for VAR_2 in ITERABLE_2:
            if CONDITION_2:
               yield EXPRRESSION

Note that you can add more levels of "for" sub-clause in a generator expression:

(EXPRRESSION for VAR_1 in ITERABLE_1 if CONDITION_1 \
   for VAR_2 in ITERABLE_2 if CONDITION_2 \
   ...
   for VAR_n in ITERABLE_n if CONDITION_n)

Also note that a double-generator expression is not a generator expression nested inside another generator expression. For example, the following code will actually result in a generator with generators as its iterable items.

( (EXPRRESSION for VAR_1 in ITERABLE_1) for VAR_2 in ITERABLE_2 )

The above nested generator expressions is equivalent to the following generator function, which is not very useful.

def f():
   for VAR_2 in ITERABLE_2:
      yield EXPRRESSION for VAR_1 in ITERABLE_1

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