List Comprehension(Python) Addiction

return ["addiction" for i in 10]

I first encountered the term list comprehension watching a talk on optimising Python code by Sebastian Witowski.

I always knew this term existed but didn’t include it in my arsenal of tools while writing personal projects.

I mean, I don’t have to right?

So long as the code work and is maintainable, I’m good.

Now look at the following code:

    output = []
    for i in list:
    	if i % 2 == 0
    	output.append(i)
    return output

Isn’t it clear and easy to understand.

There is no need for fancy one-liners.

We simply iterate through the list and only append it to the output if element i is an even number.


But as I start working on more projects, I realised that such pattern occurs over and over again - to return a subset of the list that meets certain condition.

It may not seem much if it’s just for a simple script or project.

However, as your script/project grows, all these extra lines of codes will have an impact.

The above code can be simple be replaced by:

    return [i for i in list if i % 2 == 0]

To those who are unfamiliar with list comprehension. Here is the syntax:

    [expression for i in list if condition]

It is equivalent to this:

    for i in list:
    	if condition:
        	expression

List comprehension can also be useful for assertions.

For example if we want to ensure that list in a sorted order, we could simply use:

    assert all([list[i] <= list[i+1] for i in range(len(list)-1)])

all() is an in-built function that returns a True if every element in the list is True.

So our list comprehension starts iterating from 0 to the length of the list minus 1.

Our expression, list[i] <= list[i+1], will then check if the current value of list[i] is less than the next (note that list[i] will not reach the last element). And it will return the respective boolean value.

We can also use to assert that every value in a dictionary is an integer.

    assert all([type(value) is int for key, value in dictionary.items()])