Lesson 08: List and dictionary comprehensions

This week you will learn how to create lists and dictionaries using comprehensions, compact expressions that can often be expressed in a single line of code.

Readings

Below are a set of readings that you should consider reviewing. Note that the Real Python articles referenced below may require signing up for a free account.

1.0 Required

Lisa Tagliaferri, Understanding List Comprehensions in Python 3 (DigitalOcean, Jan 2017).

Very short introduction to the topic. Once you have read Lisa proceed directly to Trey Hunner’s blog post.

Trey Hunner, Python List Comprehensions: Explained Visually (Trey Hunner, 15 Dec 2015).

What I and others like about Trey’s blog post is the way he helps the reader familiar with writing for loops transition to writing comprehensions. A must read.

Josh Robin, Dictionary Comprehension in Python 3 for Beginners (Medium, May 2019).

Josh fills in the details covering how to write comprehensions that iterate over dictionary keys and values in tandem.

Trey Hunner, Overusing list comprehensions and generator expressions in Python (Trey Hunner, 26 Mar 2019).

Warns against comprehension overuse and misuse.

James Timmons, When to Use a List Comprehension in Python ( Real Python, 22 Jan. 2024)

A more advanced comprehensions tutorial that also discusses the built-in functions map() and filter(), the new Walrus operator (:=) and generators.