Python Tutorials - Herong's Tutorial Examples
∟List, Set and Dictionary Comprehensions
This chapter provides introductions and tutorial examples about list, set and dictionary comprehensions. Topics include introduction on list, set and dictionary comprehensions; examples of comprehensions with filtering conditions and nested loops, comparison of generator expressions and comprehensions.
These sections are omitted from this Web preview version. To view the full content,
see information on how to obtain the full version this book.
What Is Comprehension
What Is List Comprehension
What Is Filtered List Comprehension
What Is Double-List Comprehension
What Is Set Comprehension
What Is Dictionary Comprehension
Generator Expression vs. Comprehension
Takeaways:
- A list comprehension creates a "list" object using a "for" clause enclosed in square brackets.
- A set comprehension creates a "set" object using a "for" clause enclosed in braces.
- A set comprehension creates a "dict" object using key:value pair expression and
a "for" clause enclosed in braces.
- A filtered comprehension is a comprehension with an "if" sub-clause
to filter out items with a given condition.
- A double comprehension is a comprehension that contains a double "for" clause
to iterate two iterables as nested loops.
- Generator expressions and list/set comprehensions have almost identical syntaxes:
(EXPRESSION for ...) vs. [EXPRESSION for ...]/{EXPRESSION for ...}
- Generator expressions return "generator" objects.
- List/set/dictionary comprehensions return "list/set/dict" objects.
- Generator expressions use "late-binding" to support next(generator) calls
to reduce memory usage.
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