Why python list comprehension are awesome

I can’t think of how many times have just wondered about how awesome the python’s list comprehensions are. I found them extremely handy while I was preprocessing data for my data visualisation project.

Let me share with you some examples, general syntax and some nifty tricks.

Simple list comprehension example

Create list of numeric values ( this example is quite useless but illustrative for beginning )

The code is interpreted as : “run interation for i, and in each iteration, append i to the list”. Therefore we can go crazy with how we are iterating. We can iterate through some list or generator. Anything that’s iterable.

Process iteration result before appending into list

We can however play much more with the results of the iterations which we put into the created list. For example we may want to create list of powers of 2. We can simply do

Or even call some function to process the result of iteration somehow.

This example gives us array of numbers saying how many characters powers of 2 got.

Use custom generators with list comprenesions

Using generators we can make our list comprehension more readable. We can define custom generator and use it

Use conditions for processing iteration result

When we receive the result from the iteration, we can do more complex things with it thanks to conditions. Like this :

Use conditions to filter out appended iteration results

When the condition in previous example is evaluated, it’s for sure that >SOME< value will be added to the list. However, sometimes we might want to filter out values we receieve from generator or iterated list. We can filter out even values

Iterate multiple variables

Note that we just constructed the list of lists. Similarly we can also construct objects or dictionary

Trick: Nested list comprehension : Flattening list of lists

We may have nested lists we want to flat out. Let’s have

To flat out, we can use nested list comprehension.

The syntax may be a bit intimidating on the first glance. If you look closer however makes perfect sence.
I’ll add parenthesis to make it little bit more readable

Now we need to realise that each element of iterated list is also list. This list element we called sublist. And then we use second iteration to iterate each element of this sublist : for item in sublist.
This is actually works pretty much the same as previous example

Leave a Reply

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