List Comprehensions in Python

List comprehension, or listcomp for brevity, is a powerful Python feature that can make your code generally look a lot cleaner and readable when building out a Python list. Let’s dive right in.

Example 1: List of Absolute Numbers

Let’s say I have a list of both positive and negative numbers:

numbers = [-1, 2, 0, -4, -10, 5]

and I want to build another list of absolute values of this numbers list called abs_numbers. There are 2 main approaches to this:

Look how much cleaner the listcomp method is!

To expand on this, let’s do something a little bit more complex. Say we want to create another list called non_zero_numbers that contains non-zero numbers only:

Example 2: Colorful Cars

Let’s do a more complex example. Let’s say you’re a car dealer, and you want to build a list of initial supply of cars with different colors. You’ll want red, blue and yellow cars from each auto brand.

Pretty straightforward. Let’s try using list comprehension.

Look how we can do this all in 1 line! No need for nested for loops.

Easy! Just swap the ordering of the for loops (do for brand in car_brands before for color in colors)

Additional Information

I first learned about list comprehensions from this book called Fluent Python by Luciano Ramalho. It’s a great resource for writing more elegant Python code.

I’ve also posted these code examples on GitHub. Feel free to clone, read and run them.

Hacker. Aspiring tech entrepreneur. Passionate about technological advancements for the betterment of humanity. https://zhenghaotan.com

Hacker. Aspiring tech entrepreneur. Passionate about technological advancements for the betterment of humanity. https://zhenghaotan.com