Python Tutorials - Herong's Tutorial Examples
∟Iterators and Generators
This chapter provides introductions and tutorial examples about iterators and generators. Topics include introduction on iterable objects, iterators and generators; list of built-in iterable data types; using 'yield' statements and generator functions; using generator expressions.
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
Takeaways:
- An iterator object supports a required instance method, iterator.__next__(), to return the next item.
- An iterable object supports a required instance method, iterable.__iter__(), to return an iterator object.
- isinstance(object, collections.abc.Iterable) can be used to
test if a given object is iterable or not.
- For built-in iterable objects, their iterators are also iterable.
- A generator iterator is an iterator object created by a generator function
or a generator expression.
- A generator function is a special function that contains one or more "yield" statements.
- A "yield" statement transforms the enclosing function into
a generator function. It suspends and resumes execution to support next(generator) calls.
- A generator expression transforms an expression into a generator with a "for" clause enclosed in parentheses.
- A filtered generator expression is a generator expression with an "if" sub-clause
to filter out items with a given condition.
- A double-generator expression is a generator expression that contains a double "for" clause
to iterate two iterables sequentially.
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
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