My Blog
Articles related to programming, computer science, technology and research.

19/04/2018 Categories: Python Programming.

Contents1 Introduction2 List Comprehensions3 Set Comprehensions4 Dict Comprehensions Introduction   Python comprehensions are constructs that create sequences from existing sequences in a clear and concise manner. Comprehensions are of three types:   list comprehensions set comprehensions dict comprehensions   List comprehensions were introduced in Python 2.0; while set and dict comprehensions have been introduced in […]

## Introduction

Python comprehensions are constructs that create sequences from existing sequences in a clear and concise manner. Comprehensions are of three types:

• list comprehensions
• set comprehensions
• dict comprehensions

List comprehensions were introduced in Python 2.0; while set and dict comprehensions have been introduced in Python 2.7.

## List Comprehensions

List comprehension is the most popular Python comprehension. It allows us to create a new list of elements that satisfy a condition from an iterable. An iterable is any Python construct that can be looped over like lists, strings, tuples, sets. In list comprehensions we use square brackets.

General syntax of a list comprehension is as follows:

Following is an example of list comprehension for creating a list of squares of numbers in range 1-10:

In the previous example, we can also use if condition to generate only squares of even numbers:

Result of above comprehension will be:

List comprehensions can be useful to perform matrix computations. Consider following matrix:

We can print the diagonal elements as follows:

We can calculate sum of elements in each row in a matrix as follows:

Let our matrix be:

We can perform transpose of above matrix by writing:

## Set Comprehensions

Set comprehensions were added to python in version 2.7. In set comprehensions, we use the braces rather than square brackets. For example, to create the set of the squares of all numbers between 0 and 10 the following set comprehension can be used:

## Dict Comprehensions

Just like set comprehensions, dict comprehensions were added to python in version 2.7. Below we create a mapping of a number to its square using dict comprehension: