Python List comprehension is a very easy and quite compact syntax used for creating a list from another list or a string for that matter. It is thus, in turn, a very concise way to generate a new list by performing operations on every item in the existing list. Thus, list comprehension is practically very fast, comparing to when processing a list using for loop. Also, the list comprehension offers a compact and short syntax when generating a new list based on values from an existing list. In this post, thus, we will learn about Python List Comprehension.

List Comprehension — What is it?

As we know, the basic idea behind list comprehensions is to take a group of elements. Then, modify the elements in the way you like, and also return them to a list.

Thus, the idea of a simple list comprehension looks like :

[do_this for each_item in group_of_items]

In layman terms, thus, the do_this part represents what I want as my output. The each_item part represents the iterables. Also, the group_of_items  generally represents input, or on what we shall be iterating on. Most commonly it generally is a list, it can also be a tuple or a dictionary or for that matter, anything on which we shall be iterating over.

A fact to note also, after do_something is, it looks and works in the same way as a for loop generally does. So, in turn, it is similar to:

for each_item in group_of_items:
    do_this

Thus, we should understand that whatsoever be the input, or whatever function or operation one performs on the input, the output always is a list comprehension. Also, it will ever-always be a list, as its name says it as “list comprehension”.

How do we use Python List Comprehension

We have till now got a basic idea about what a list comprehension is. So, now, lets look for its working and see the big picture. Let’s take and example :

num = [10, 11, 12, 13, 14, 15]

Thus, you can see here, we have taken a list of numbers. And, then, we want to generate a list from it which multiplies each number with 2. For this, we may use a for loop like :

new = []
for number in num :
    number * = 2
    new.append(num)

The new list now looks like :

[20, 22, 24, 26, 28, 30]

Obviously, this is great as the work is done rightly. But, now lets look at how to do this using list comprehension. It works like :

new = [num * 2 for number in num]

Great !! Thus, Its done. Also, you see that we have reduced the 4-lined for loop into a single line. We have made it comparatively very very easy. We also don’t have to worry about any  for loop. Or also the trouble of creating an empty list and then adding or should I say appending each element individually. Isn’t it easy? What do you say?

Guess what? We can do more complex things beyond just simple addition, subtraction, multiplication and division, i.e. basic calculations. Lets take a new example using the same list num as above :

new = [round(num / 4) for number in num]

Thus, what are we doing in this example? Let me explain. We are taking the numbers from the num list, then, divide it by 4 and further round the resultant to its nearest integer value

So what does the results look like. Lets see. Here, it is :

[2, 3, 3, 3, 3, 4]

Further, List Comprehension Applications

Now, furthermore, we want to assign letters in alphabetical order to the numbers in the list using the list comprehension method. Lets see how to do it.

num_to_alphabets = 
{
    10: 'j',
    11: 'k',
    12: 'l',
    13: 'm',
    14: 'n',
    15: 'o',
}
alphabets = [num_to_alphabets [num] for num in num_to_alphabets]

The alphabets list will now output to:

['j', 'k', 'l', 'm', 'n', 'o']

We may have even done the same with calling functions within a list comprehension. A list comprehension is particularly useful when we need to implement a complex function on a group of elements.

Lets take an example :

num = [5, 8, 9, 15, 6, 17, 4, 2]
new = []
for number in num :
    if number >= 5 :
        new.append(number)
    elif number == 9 :
        new.append('nine')
    else:
        new.append('small')

This code will return the following list for new :

[5, 8, 'nine', 15, 6, 17, 'small', 'small']

Now see the list comprehension for the same :

new = [number if number >= 5 else 'nine' if number == 9 else 'small' for number in num]

===> AT THE LAST ROUND

Through this article, I have tried to explain to you the concept of Python List Comprehension. Also, thereby, providing you with the knowledge about what exactly is List Comprehension. How it works and also, how to write a List Comprehension for any function or method or instruction whatsoever. By and through this article, thus, I suppose I have made myself pretty clear. But, in case, you still have some doubts lingering. Then, please do write to me in the comments section and I am as always, ever-ready to help you. And, also solve your many queries and problems.

Python List Comprehension

Until then bidding you Good-Bye !!! Ok, wait ….. before you go, you may check out my various other posts. Also, for the simple reason, that is, to enhance your knowledge on various other topics of importance. Where ??? Here……

Categorized in: