## 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:

1 2 3 4 |
[expression for item1 in iterable1 if cond1 for item2 in iterable2 if cond2 ... for itemN in iterableN if condN] |

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

1 |
s=[x*x for x in range(1,11)] |

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

1 |
s=[x*x for x in range(1,11) if x%2==0] |

Result of above comprehension will be:

1 |
[4, 16, 36, 64, 100] |

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

1 |
m=[[1,1,1],[2,2,2],[3,3,3]] |

We can print the diagonal elements as follows:

1 |
[m[i][i] for i in range(0,3)] which prints [1 2 3] |

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

1 |
[sum(row) for row in m] which prints [3 6 9] |

Let our matrix be:

1 |
m=[[1,2,3],[4,5,6],[7,8,9]] |

We can perform transpose of above matrix by writing:

1 2 3 |
[[row[i] for row in m] for i in range(0,3)] which gives: [[1, 4, 7], [2, 5, 8], [3, 6, 9]] |

## 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:

1 2 3 |
>>> x = {i**2 for i in range(10)} >>> x set([0, 1, 4, 81, 64, 9, 16, 49, 25, 36]) |

## 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:

1 2 3 |
>>> x = {i:i**2 for i in range(10)} >>> x {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} |

## Leave a Reply