Comprehensions in Python

Python allows you to create in a fast-writing, highly readable and functionally efficient way lists, dictionaries and sets, that’s what we call comprehensions, fast-writing programming. In this post, we will see some examples of comprehensions in Python.

List Comprehension

A list is an ordered array of items, It can have duplicate values and any type of data such as strings, sets, integers, etc. For this example we’re going to use integer types using list comprehension. The list comprehension is declared following the next structure:

var_name_list = [iter_var for iter_var in list condition(optional)]

To see how list comprehension works, Let’s suppose we want to create a list with all odd numbers up to 100, we can programming the same solution in two different ways.

First, we can create an empty list, then iterate from 0 to 100, divide by 2 every number and if the remainder of dividing by 2 is diferent from 0 we add the number to the list.

Or we can rewrite the code above using list comprehension, just like this:

Dictionary Comprehension

A datadictionary is key-value collection. It means that when you want to storage a value, you must assign an unique key to do it and when you want to access to the value, you must use the key that it was assigned.

The Dictionary Comprehension help us to create new dictionaries from other dictionaries, usually it follow the next structure:

var_name_dict = [operation for (key, value) in other_dict.items()]

To see how dictionary comprehension works, let’s suppose we have a dictionary “fruits” with the cost per unit for some fruits and we want to create a dictionary “tax_fruits” with the total price for each fruit in the dictionary “fruits” . The total price is equal to add the price and the price multiply by 0.02, when 0.02 represents the 2% profits from the store.

We can programming the same solution in two different ways. First, we can create an empty dictionary, then iterate for each of the items, calculate the total price and storage the key-pair item.

Or we can rewrite the code above using dictionary comprehension, just like this:

Set Comprehension

A set is an unordered collection of items, where every item in the set is unique. The set comprehension has a very similiar structure to the list comprehension.

var_name_set = {iter_var for iter_var in set condition(optional)}

To see how set comprehension works, Let’s suppose we want to create a set with the powers of two from 0 to 9, we can programming the same solution in two different ways.

Or we can rewrite the code above using set comprehension, just like this:

Software engineer with 3+ years experience.