List, set and dictionary comprehension in python

List, set and dictionaries are some of the important data types in python. In these article we shall see the comprehension techniques of these data types.

What is comprehension in python?

Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined. Python supports the following 4 types of comprehensions:

  • List Comprehensions
  • Dictionary Comprehensions
  • Set Comprehensions
  • Generator Comprehensions

We shall see the first 3 with an example for each.

List comprehension

The following snippet is a perfect example for list comprehension. This list comprehension will generate a list of numbers from 1 to 10.

list comprehension

If we print numbers, it will print something like this.

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

Let us compare this method to the traditional method to really understand how simple list comprehension makes our code. This is the same code for the above example without list comprehension.

python traditional for loop

In list comprehension the list declaration, looping, adding elements to the list all takes place in a single line of code.

Set comprehension

As we all know a set will have elements within the curly braces. The following code is an example for set comprehension.

set comprehension in python

And the output will look like this.

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Dictionary comprehension

The dictionary will have a key, value pair. In this example the key is number from 1 to 5 and their values are corresponding square numbers.

Dictionary comprehension in python

And the output is,

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}


Comprehensions reduces the code size and complexity considerably. Make sure to use them in your upcoming codes.

Simple is better than complex!

Leave a Reply

Your email address will not be published. Required fields are marked *