List Comprehensions in Python

14th Aug 2017

Language Features

python

Recently I was looking at Peter Norvig's essay on a Sudoku solver in Python (which can be found here) and found his use of Python's list comprehension functionality to be pretty interesting. Having learnt Java as a first language, when it comes to iterating through lists and working with the individual values the following format is the first that comes to mind:

int[] a = {...};
int[] b = {...};
ArrayList<int> c = new ArrayList<int>();

for (int i = 0; i < a.length; i++) {
    for (int j = 0; j < b.length; j++) {
        if (a[i] != b[j])
            c.add(a[i] + b[j]);
    }
}
return c;

Or perhaps for (int i in a). However, Python offers succinct methods of working with lists that make things a lot easier, and once you learn the syntax make the code a lot more readable. For example, the previous code in Python can be written as:

return [x + y for x in a for y in b if x != y]

These list comprehensions are extremely useful for many things, such as matrix operations:

def cross(A, B):
    return [a + b for a in A for b in B]

The way the syntax is laid out means that the 'sentence' reads easier, and is almost an English sentence on it's own. Also, because it's so compact it makes quickly writting tests so much easier, for example to test if element in a list correctly passes through a function (in this case the square function), the following could be written:

assert all(square(x) == x*x for x in X)

While I've barely scratched the surface of the power of list comprehensions in Python it's plain to see that this functionality is invaluable and I find myself wishing such features were available in other languages whenever such a problem arises that would be perfect for them.