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.

4 thoughts on “Python Tutorial – List Comprehensions

  1. I think you are missing a core concept here: functional programming. And with it, immutability. I agree that the syntax of Python’s list comprehensions might not be ideal. Just saying that nested loops are always easier to reason about than multiple expressions in a list comprehension still rubs me the wrong way.

    With functional constructs you don’t (or at least shouldn’t) mutate anything, you get new collections back. With imperative nested loops which change the guts of things all over the place it gets hard to see what’s going on very quickly.

    Also, I think multiple expressions in comprehensions are more readable if you put them in separate lines:

    new_list = [number for row in numbers
    for number in row]

    1. Thanks for the comments. You’re correct – I did not speak about FP immutability since it was not the point I was after. That’s the other aspect and subject for different post ­čÖé

Leave a Reply

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

four × five =