List Comprehensions in Python

Lists are a versatile Python data structure and allows various sequence operations. Besides the usual, Lists also include a powerful operation called as ‘list comprehension’ which allows us to process various list structures, like a matrix or nested arrays or lists. It allows you to concisely form a new list by filtering the elements of a list.

List comprehension takes the following form.

Which is equivalent to the following for loop.

Take the example matrix given below.

It is easy to get rows from the matrix as they stored in a row format, like given below.

But what if you wanted to grab the columns from the matrix. Here we can use list comprehensions. List comprehensions are a way to build new lists by running a expression on each element in the sequence.

The first line above basically asks to give us the item at location row[0] (first item in the row) for each row in the matrix which is than stored in the new ‘col1’ list. So for example on the first iteration of the matrix row[0] will return ‘1’, on the second iteration it will return ‘4’ and lastly ‘7’.

We can also make list comprehensions more complex.

Note: list comprehensions has to be in square brackets which basically hints that a list is returned. The following for example will not work.

You can also add a filter condition to the expression.

This is just a introductory article around list comprehensions, as they are more powerful in what they can accomplish. We will cover them more in future articles.


You can test your Python code using the online code editor.

Leave a Reply

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