Better Programming

Advice for programmers.

Member-only story

8 Things to Know to Master Comprehension in Python

Yong Cui
6 min readFeb 28, 2023

--

Photo by Sam Moghadam Khamseh on Unsplash

Comprehension is regarded as one of the most Pythonic techniques. There are multiple forms of comprehension, such as list comprehension and dictionary comprehension. In addition, each comprehension has a variety of permutations, such as using nested for loops and applying a filtering condition. In this poster, I’m going to cover all essential knowledge about comprehension.

As a heads-up, for the most part, I’ll use list comprehension to show the pertinent techniques, but it should be noted that these techniques are also applicable to other forms of comprehension (e.g., dictionary comprehension).

1. Basic Form of List Comprehension

The basic form of list comprehension is [expression for x in iterable]. In this form, the iterable represents a data variable that can yield multiple items and x represents each item. The expression typically uses x and evaluates to a value that becomes an item in the resulting list object. See the code snippet for a simple example.

numbers = [2, 4, 6, 8]

squares = [x*x for x in numbers]

assert squares == [4, 16, 36, 64]

--

--

Yong Cui
Yong Cui

Written by Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).