Python Comprehensions and Generator Expressions
Published by O'Reilly Media, Inc.
An introduction to two powerful and often misused Python features
In this course, you’ll:
- Identify opportunities to refactor your code into a comprehension
- Identify places a generator and a reducer function could be used
- Discover how to use comprehensions and generators to improve your code’s readability and efficiency
Creating one list out of another list is a very common thing to do in Python—so common that Python includes a special construct just for this purpose: list comprehensions. List comprehensions can make for more readable and more maintainable Python code.
Join expert Trey Hunner to learn about list comprehensions, set comprehensions, and dictionary comprehensions and how and when you can slightly tweak comprehensions to turn them into more performant generator expressions.
What you’ll learn and how you can apply it
- Turn loops into comprehensions
- Use generator expressions
- Know when comprehensions and generator expressions should not be used
This live event is for you because...
- You’re a new Python user who wants to write more maintainable Python code.
Prerequisites
- A computer with Python 3.7+ installed
- Knowledge of variables, functions, and loops in Python
Recommended follow-up:
- Read “Comprehensions, Iterables, and Generators” (chapter in The Python Apprentice)
Schedule
The time frames are only estimates and may vary according to how the class is progressing.
Review of loops (30 minutes)
- Presentation: Review Python’s for loops
- Hands-on exercises: Explore loops
- Q&A
Turning loops into comprehensions (30 minutes)
- Presentation: How comprehensions work; two common forms
- Hands-on exercises: Explore comprehensions
- Q&A
- Break
More advanced comprehensions (30 minutes)
- Presentation: Multiloop comprehensions; dictionary and set comprehensions
- Hands-on exercises: Explore deep comprehension refactoring
- Q&A
Generator expressions (40 minutes)
- Presentation: Generator expressions and how generators work
- Break
- Hands-on exercises: Explore generator expressions
- Q&A
When to use comprehensions (35 minutes)
- Presentation: Generator expressions are for mapping or filtering; avoiding overuse of comprehensions; generator expressions often pair with a “reduce”-like operation
- Hands-on exercises: Explore refactoring
- Q&A
What to learn next (15 minutes)
- Presentation: Generator functions are even more powerful
- Hands-on exercise: Try out a generator function
- Q&A
Your Instructor
Trey Hunner
Trey Hunner helps Python programmers level up their skills through corporate training and through Python Morsels, a Python skill-building service for individuals and small teams. Trey also sends out a new Python tip every week through his email newsletter at pym.dev/newsletter.