I didn't know this term "comprehensions" when I started reading Chapter 6 of Python 101 by Michael Driscoll. Here's what i learned: Comprehensions are methods for creating lists, dictionaries, and something called a python set. I explore my newfound understanding of comprehensions further below, but one important note here is that code I've seen from others where I've thought positively "that's really concise code!" were frequently using comprehensions, so I feel like I'm gaining a superpower now!

List Comprehension

One-line for loop that makes a python list data structure. An example would be:

x = [i for i in range(5)]

If I want to print(x), I'll get the following result: [0, 1, 2, 3, 4] – i.e. a list.

An example given in the book is trying to find a string in a line.

if [i for i in line if "SOME TERM" in i]:
# do something

And this section of code shows how you can easily convert a list of strings to a list of integers.

x = ['1', '2', '3', '4', '5']
y = [int(i) for i in x]
[1, 2, 3, 4, 5]

Dictionary Comprehensions

Same idea as the list comprehensions, except at the end you have a python dictionary with key: value pairings. An example from the book is below:

print( {i: str(i) for i in range(5)} )
{0: '0', 1: '1', 2: '2', 3: '3', 4: '4'}

In order to better understand what was happening here I made a modification where I multiplied the key value of i*2, which produced keys of 0, 2, 4, 6, and 8.

print( {i*2: str(i) for i in range(5)} )
{0: '0', 2: '1', 4: '2', 6: '3', 8: '4'}

Python Set Comprehensions

First, what is a python set? In brief, it appears to be a list with no duplicates. So, as an example, if I have a list like the following:

my_list = [1, 2, 2, 'red', 'blue', 'red', 'yellow']

and then I turn it into a set like so:

my_set = set(my_list)

Then my_set will just be unique values within my_list. So print(my_set) returns:

{1, 2, 'yellow', 'red', 'blue'}

The comprehension part of this happens if you were to build the set like this with curly brackets:

my_set = {j for j in my_list}

Also of note, duckduckgo.com returned this gem of a blog post from 2006 that explains extraction of unique values from a list and computation speeds.


It really is wonderful to see how these can be created in a shorthand version of code. I think I've written much longer and more verbose workarounds to do the same thing this does in one line (specifically I'm thinking about a beautifulsoup scraped table that I manually built a csv out of instead of using a comprehension).

Realizing you've written crazy code in the past is probably a good sign of progress.