Wednesday, November 9, 2016

Python List Comprehension Simplified


This is going to be as simple introduction to Python List Comprehension.

A "list comprehension" in python provides a concise way to create lists. Basically, it nests 'expression', 'loops' and 'conditions' within a list on a single line. The basic structure of the python's list comprehension is like this: [*expression*  *for object in loop*  *if condition*] - without the "*" of-course.


Assuming we have a list called "my_list" and we want to get the length of individual elements within the list, a 'for' loop can do it as follow:-

When you run above code it will output the result as: 4 10 2 5 1 2

Now lets use "list comprehension" to achieve the same result as above:-

The result returns a list of the lengths like so: [4, 10, 2, 5, 1, 2]

Note that we didn't add a condition to the list comprehension above. len(item): is the expression value and for item in my_list: is the loop part of the "list comprehension". We will add a condition in a moment.

List comprehension has two quick noticeable advantages over using the "for" loop namely:-
1) the code is shorter in length.
2) the result is in an object list instead of individual numbers as obtained using "for" loop.

To add a condition, we simply add an "if" statement to the end of the "list comprehension" as follow;-
Lets add a condition to display only length of items greater than four: if len(item) > 4. Add that syntax to the end of the "list comprehension".

The result returns a list of the lengths greater than four like so: [10, 5]


Even though "list comprehension" may sound very nice to use it has a little draw back in the sense that it can easily make your code very difficult to read in the nearest feature.

Imagine a situation where you compressed hundreds lines of code using "list comprehension" into a few lines. It become unreadable or difficult to read when time passes.

So use it with caution.

Thank you for following the blog post.


  1. Nice post. I have learned a new way to make my code shorter.
    That's why Python is the best. Makes things easier.

  2. Very well,thanks now i know why python is bit interesting

  3. Very well,thank that why python is bit interesting