List Comprehension is a powerful feature in Python to achieve more with fewer lines of code. Its purpose is to create lists in a concise way. List comprehensions always returns a new list. You can write code in other ways also. However, list comprehension allows you to achieve the same results in one or two lines code. Let’s start with an example.
Convert a list that contains [[1,2,3], [4,5,6]] to a new list [1,2,3,4,5,6]
If you are not familiar with list comprehension, you typically end up writing something like this:
What’s boiling behind the hood? That’s the purpose of this blog. So, continue reading.
We saved a few lines of code using the list comprehension. You might be thinking what’s the big deal. Let me tell you that we only scratched the surface of the power that list comprehension flexes.
To put this in relative terms, I was asked to migrate a ton of legacy code in the year 2011. The lines of code in one particular program ran almost three full pages. I was able to convert that into 4 lines of code using list comprehension.
Some might argue that in the interest of concise programming, we may be compromising the readability. I do not object. I think that this concern can be addressed by adding some decent lines of comments articulating what the concise code is supposed to do.
I will give some examples here that I hope might ignite your interest and motivate you to use list comprehensions more and more.
You can do a lot with this feature.
If someone asks you to filter the initial_list above to produce only [1,2,3,4], how will we approach that?
You can combine filtering with a list comprehension.
The typical legacy way of writing this code is:
Given a list [1,2,3,4,5], we want to find the squares of numbers that are odd.
We can do this easily using list comprehension
We can write the same thing without using the list comprehension
At a high level, we can classify the actions into three different classes.
The iteration portion of the mechanics spits the element and put it in the variable x:
The filter part of the operation prevents all values from going into variable x. The filter filters out even numbers, causing only odd numbers to land in x.
The last but not the least is the transform part, You can do anything with it. You may square, cube, or use altogether another function in the place of the transform section of this operation.
In the example above, we are doing a square operation
It’s interesting that you can use filtering even within the transform section of the operation. Look at this example,
Here you are focused on getting a square if the number is even. Otherwise, you want a cube of the number.
If you use condition in the “filter” part of the comprehension, then you will only get a subset of numbers for you to transform. This is not what you want for this use case. Using filtering in the transformation section, you are able to transform each number differently according to a condition!
As I mentioned earlier, you could do anything with the transform part of the comprehension. Sky is the limit!
It does not always have to be dealing with numbers.
Here is one example of string values. what if you want to count unique characters in a phrase?
- I know we used a couple of additional features in Python here such as “enumerate” and “sets”.
- I will be writing a blog with some examples of these features very soon
- Please let me know if you want me to add some touch programming challenges using list comprehensions. Your comments would definitely motivate me to serve you better.
What if you want to produce a list of sets such that each set must contain a number from the left list and its corresponding square from the second list. How would you go about it?
I skipped the solution part intentionally.
I like history. But I like to always list the history part of any technical stuff at the end. This is in stark contrast to what you may find in other technical blogs. The reason I do that because it helps someone to look into the history part only if he or she is interested further after munching on a couple of technical bits.
According to Wikipedia, List Comprehension is a syntactic constraint available in some programming languages for creating a list based on existing lists.
It follows the form of the mathematical set-builder notation (set comprehension) as opposed to using map and filter functions,
- You see the story behind the picture! Don’t you?
Transform | Iterable | Filter
This was introduced in Python with 2.7 and 3.x versions.
The SETL programming language (1969) has a set formation construct which is similar to list comprehension.
Some intelligent person has all this figured out even before some of you were born!
The history section of this blog was extracted from