Loop Better: Generators, Comprehensions, and More

By Trey Hunner

Elevator Pitch

You know Django and you know Python, but do you know how to choose between using a for loop, a comprehension, and a generator function?

Let’s get hands-on experience using Python’s various looping idioms and improve our skills at deciding when to use each one.

Description

You’ve used lists and loops, but do you really understand how they work? Do you know how to make your own “iterable” object?

During this workshop we’ll dive into the contract that Python uses to make loops work and we’ll see how we can use this contract to make our own code more readable, more efficient, and more flexible.

During our journey together, we’ll cover:

  • Comprehensions
  • Generators
  • The Iterator Protocol
  • Duck typing

This is a hands-on tutorial. We’ll be working through many short exercises together so make sure to bring your laptop.

This tutorial is aimed primarily at programmers who been using Python already but have not yet dived deeply into generators and the iterator protocol.

Notes

Outline

  1. Generator Functions (30 minutes)
  2. The Iterator Protocol and Duck Typing (30 minutes)
  3. List Comprehensions & Generator Expressions (60 minutes)
  4. Iteration helpers (itertools and more) (30 minutes)
  5. Creating custom iterables (30 minutes)

About half of the tutorial will involve hands-on exercises. I am planning on 6 exercise periods, approximately 15 minutes each.

This tutorial is based on material from the Intermediate Python course I teach through my training company, Truthful Technology LLC.

This tutorial includes a few of my favorite Python topics to teach during my training courses. <3