List Comprehensions

Sometimes a programming design pattern becomes common enough to warrant its own special syntax. Python’s LIST COMPREHENSIONS are a prime example of such a syntactic sugar.

List comprehensions in Python are great, but mastering them can be tricky because they don’t solve a new problem: they just provide a new syntax to solve an existing problem.

What are list comprehensions?

List comprehensions are a tool for transforming one list (any ITERABLE actually) into another list. During this transformation, elements can be conditionally included in the new list and each element can be transformed as needed.

It can be used to construct lists in a very natural, easy way, like a mathematician does. Comprehension lists provides a great way to create lists and as you move ahead with the examples, you will realize its importance.

Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

A list comprehension consists of brackets containing an expression followed by a FOR clause, then zero or more FOR or IF clauses. The result will be a new list resulting from evaluating the expression in the context of the FOR and IF clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal.

A list comprehension consists of the following parts:

  • An Input Sequence.
  • A Variable representing members of the input sequence.
  • An Optional Predicate expression.
  • An Output Expression produces elements of the output list from members of the Input Sequence that satisfy the predicate.

List comprehensions can contain complex expressions and nested functions:


>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

In order to create a comprehension list, you will use brackets that consists of a for clause and then it may or may not have more for or if clauses. Comprehension lists always return a list.

Look at the following example:

Now this is how it will look when you use comprehension list

So, in other words, comprehension lists are a more concise way of creating lists. Comprehension lists can be applied on functions as well. Consider the function square_root in the following example:

Now let’s see, how we can apply comprehension list to this function

Comprehension list can also be applied to files. In this example, we apply comprehension list to football.txt file created in the chapter on Generators.

So, do you have any scenario where you would like to imply list comprehensions? It’s high time for you, give it a try.


Enroll for Instructor Led Live PYTHON TRAINING


Get Updates on Tech posts, Interview & Certification questions and training schedules