Python List Comprehension in a Nutshell

check boxes

List comprehension in Python is perhaps the most celebrated, and often is abused the most, feature ever. It provides us with a concise way to write Python list an abbreviated form. It is also one of the reasons why Python is able to consolidate thousands of lines of code into mere hundreds. Not only does list comprehension provides the ease of readability of many lines into one, it misses not one less functionality compared to its original form.

As describe by the official Python developer’s guide:

(list comprehension) is proposed to allow conditional construction of list literals using for and if clauses. They would nest in the same way for loops and if statements nest now.

PEP 202

In this tutorial, we will look at different ways of using Python list comprehension. Hopefully by the end of this tutorial, you will have all you need to know to master and start using list comprehension in your next Python project!

Simple Form

This is list comprehension in its simplest form. A single for loop which is written after the variable of interest, all within a bracket. As you can see, both the original and comprehensive form produce the same result, however with list comprehension, a 4-liner code is now reduced to 1 line.

Nested Form

Time for loop-ception. We can apply the same concept for double loop arrays, saving us a 7-liner code into well…you guessed it, a 1-liner code; the sky is the limit here. Heck, you could even write a 5 loop with 5-d array if you really want. But let’s not get too ahead of ourselves here and start with this 3×3 array.

Example 1

Example 2

Conditional Form

What if I have if conditions in the loops? No problem, list comprehension also got this covered.

Example 1

Example 2

Lazy Form?

lazy cat
Ain’t nothin wrong with being lazy

There are days when you just want to take a slow day and type as little as possible, or your eye is strain from reading too many lines of code. Here comes a hack, list comprehension can even be used without an assignment!

Tuple Form

List comprehension extends to its Tuple cousin as well! You can even mix-and-match list and tuple together (highly useful in a lot of cases).

Dict Form

Last but not least, list comprehension extends to Python dictionary.

Closing Thoughts

There are multiple reasons why Python is one of the most popular programming language of our recent times. Its ease of readability, code-ability, and all-in-all friendly towards programmers of all levels, from beginner to very advance. As exemplified above, list comprehension here continues to reassure our love for this language.

Want to learn more about programming? Be sure to check out even more interesting articles like this here.

Start the discussion

Leave a Reply

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