Tag Archives: list

Python Tutorial – List Comprehensions

PythonThis Python Tutorial post will introduce a very cool technique for Object Oriented guy like me: List Comprehensions. It provides way to create new lists while doing some operations to elements in the list.

List Comprehensions

Lets take a simple example how you would create a list of numbers in a range multiplied with two. Quite school example, but hang on.

This gets the job done. For object oriented guy this would be standard way to do this. There’s luckily shorter way to do same with comprehension.

Inside brackets first part is expression and after that there is for clause. Comprehension can has an optional part that can contain zero or more for and if clauses.

Here is an example of if clause in list comprehension.

Now comes the part that things get a bit ugly. Here are two versions of flattening loops.

I find the first version completely unusable because it looks very messy. I would gladly use latter version because you can understand it with one glimpse.


I started this post with saying that List Comprehensions are cool. They still are and somewhat usable way to shorten your code.

List Comprehension comes with a price. They are almost always harder to read than their clearer versions. Think twice before writing something just for less lines of code.