Build your lists using list comprehensions

Build your lists using list comprehensions

A common way to build lists in a program that we see is this construct

The basic construct here is that by looping over something (an iterable or a condition) we add items to our list. I’m sure you’ve been there and have already used this construct in some of your code.

There is of course a more Pythonic way to do this, otherwise I wouldn’t have made a post about it. Let’s meet list comprehensions. At first they will seem complex and difficult to read and sometimes I write one or see one that still is! But they are actually very neat and easy to use.

The above example written as a list comprehension:

Admit it, looks neat doesn’t it?

Let’s examine our list comprehension, the basic structure is this:

Starting from the inside out, we have an iterable that we loop over by using a basic for element in iterable  construct. Instead of using this construct as a classic for-loop where we append a body after the semi colon, we place our return element  in front of our loop construct. All of this is then surrounded with square brackets to indicate our intention of creating a list.

Structure of list comprehensions
Structure of list comprehensions

If we create the most basic list comprehension, we are just duplicating our original iterable:

The real beauty lies in the fact that we can modify our element before putting it in our new list:

By using the element in an expression we can modify it before putting it in our new list. Some more examples:

The official Python documentation on list comprehensions

One Reply to “Build your lists using list comprehensions”

Leave a Reply

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