Making Python code more readable with list comprehensions


This post is added as a reference for myself.

As I mentioned previously I’ve been spending a good deal of time learning how to write efficient and readable Python code. Jeff Knupp’s Idiomatic Python videos are absolutely incredible and have definitely helped me become a better programmer. In his first video he turned me on to list comprehensions and how they can make code more readable. Prior to watching this video I had a tendency to use multi line iterators similar to this:

def lower_a_list(list):
    ml = []
    for word in list:
        ml.append(word.lower())
        return ml

After watching Jeff do some crazy awesome python sorcery on bad.py I’ve started to use list comprehensions. Here is a refactored lower_a_list() that uses list comprehensions:

def lower_a_list(list):
    return [word.lower() for word in list]

I find the second much more readable and you can get the gist of what’s going on by scanning from right to left. Huge thanks to Jeff for putting out this amazing series!

This article was posted by Matty on 2016-10-21 16:40:00 -0400 -0400