Master List and Dict Comprehension with Python

What will we cover?

What is List Comprehension in Python. We will demonstrate how to make List Comprehension and show how this also work with dictionaries, called, Dict Comprehension. Then show how Dict Comprehension can be used for frequency count.

Step 1: What is List Comprehension?

List Comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists.

It is easiest to demonstrate how to create it in Python (see more about lists and about foo-loops).

my_list = [i for i in range(10)]


Will result in.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Here you use the range(10) construct, which gives a sequence from 0 to 9 that can be used in the Comprehension construct.

A more direct example is given here.

my_new_list = [i*i for i in my_list]


Which results in the following.

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Step 2: List Comprehension with if statements

Let’s get straight to it (see more about if-statements).

my_list = [i for i in range(10) if i % 2 == 0]


This will result in.

[0, 2, 4, 6, 8]

Also, you can make List Comprehension with if-else-statements.

my_list = [i if i % 2 else -i for i in range(10)]


This results in.

[0, 1, -2, 3, -4, 5, -6, 7, -8, 9]

Step 3: Dict Comprehension

Let’s dive straight into it (see more about dict).

my_list = [i for i in range(10)]

my_dict = {i: i*i for i in my_list}

Which results in.

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Notice, that the lists do not need to contain integers or floats. The constructs also works with any other values.

Step 4: Frequency Count using Dict Comprehension

This is amazing.

text = 'aabbccccc'

freq = {c: text.count(c) for c in text}

Which results in.

{'a': 2, 'b': 2, 'c': 5}

Notice, that here we will recount for each instance of the letters. To avoid that you can do as follows.

text = 'aabbccccc'

freq = {c: text.count(c) for c in set(text)}

Which results in the same output. The difference is that you only count for each letter once.

Step 5: Want more?

I am happy you asked.

If this is something you like and you want to get started with Python, then this is part of a 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.

See the full FREE course page here.

Leave a Reply