Thanks to visit codestin.com
Credit goes to pyofpython.wordpress.com

List Comprehension

List Comprehension is one of the most powerful features of List which is used to create a new list from other iterables using a single line. Although it’s a very powerful and distinctive feature, I always suggest using List Comprehension whenever it is required. This is because List Comprehension does make your code to look elegant, but, at the same time, it’s harder to interpret and read. Let’s begin with this interesting feature. 

The task is to write a python code to generate a square of first 10 numbers. The task is very simple. Before using List Comprehension, let’s code it down using simple for loop, as we have used earlier while understanding for loop structure.

Using for loop in lists:

What we have done is that first we have created an empty list to store the square of numbers. The name of this list is square_list. There are 10 numbers which are represented by “i”. So “i” will be having one value ranging from 0 to 9. This is written in line two of the code. It can be read as “for the value of i which ranges from 0 to 9”. In the third line of the code, we will multiply the value of “i” with itself to generate the square and then we will store the multiplied value in empty list, square_list. The first value of i = 0 and its square is also 0. This is shown in the first output line. The second value of i = 1. Now we have to store this result along with the previous result. That is, we have to append the results. Hence we are using the append () function. I think it’s a clear concept of when to use append ().

Let’s write the code using List Comprehension.

WOW!!! That’s really amazing. But, what happened actually? If you compare the two codes, you’ll observe that nothing fancy happened here. The generalized format will help to understand what has just happened here. When we’ll Google it, the syntax of comprehension list can be written as follows:

List_comprehension = [expression for member in iterable]

There are three words:

Expression: can be the member itself, a call to a method, or any other valid expression that returns a value. Here, the expression i * i is the square of the member value.

Member: can be the object or value in the list or iterable. Here, the member value is i

Iterable: can be a list, set, sequence, generator, or any other object that returns its elements one at a time. Here, the iterable is range (10).

OK. Now these are some weird stuff to understand. Let’s understand in English.

There are n elements in the list and I want each n element to get squared, i.e. n * n. I can say that, I want n*n for each value of n which is in the given list_variable”. The words which are in bold font, let me take these out and put it in square brackets. 

[n*n for n in list_variable]. Assign this to a variable. Bingo!! This is list comprehension. 

Let’s try for some more examples. I’ll explain in detail and I’ll also try to write like english sentences.

# Write a program using List Comprehension to print the sum of all digits from an alphanumeric string.

Solution: What should be the algorithm?

  1. There is an alphanumeric string containing both characters and numbers.
  2. Let all these be some value say, “i”.
  3. We want int(i) and we have to check if this int(i) is a digit or not and if it is present in the input string or not. 
  4. Finally, we have to take the sum of all these values of “i” and print the sum.

Let’s code it down now,

So, this is my input string. You can also use input commands to prompt users to enter the string at runtime. In English, it goes like, “I want integer values of I for each value of I in my data after checking that if I is a digit.” Let’s code it down.

As one can see, we are getting the numbers but it’s more like a list. This is not what we wanted. My list is having the value 33 and it’s giving 3, 3. In this case we need a function called split (). What does this .split () do?

So, it’s separating or splitting everything. All these values are equal to “i”. And our requirement is to get all those values of “i” which are digits. Let’s incorporate this function in our list comprehension.

Now it’s working correctly. I think now it’s clear what the above code is doing. Before calculating the sum, let’s do one more check: the need of specifying int. Can we write float(i) or i only?

So, it’s working with everything, with and without specifying int. But it’s a good practice to specify the data type to avoid any unwanted errors. Now, let’s calculate the sum.

And finally, we are printing the result after taking the sum using the sum function. 

Take another example.

# Write a program using List Comprehension to determine whether the grade of a student is above A+ or not. Ask the user to enter the number of subjects at runtime and the marks of subjects should be one space-separated.

Solution: What should be the algorithm? As per the question requirement,

  1. First, the number of subjects has to be entered. Since, it has to be in run-time, input () function is required. And it has to be an integer also. 
  2. Secondly, the first mark will be entered and before entering the second mark we need a space. Split () function will help.
  3. Then, the average of marks is required. Mathematically, average = total marks/ total subjects. Sum() function will give the total marks and the total number of subjects is already determined above. 
  4. Finally, average obtained can be compared with some reference value using if loop.

Let’s code it down now,

As discussed in step 1, we have taken a variable total_subjects and have prompted the user to enter the total number of subjects at runtime. Here, the subjects entered are 5.

This will display a message that please enters the marks obtained in 5 subjects.

Now comes the conceptual part. marks is the variable used to store the result. “i” has 5 values, because there are 5 subjects. i in input() is the number of subjects. i = 1st subject and then it’s marks will be entered. Then, the for loop will be executed for 2nd value of i, that is, i = 2nd subject and then it’s marks will be entered. Now these two marks can be separated by splitting them one space apart. Then the for loop will be executed again. This will go on till all 5 subjects marks have been entered and then split by a space. As shown earlier, specifying int is optional, but it will help to know the system that integer values have to be entered. Let’s calculate the average now.

Finally, the average is calculated and the result is displayed. 

This is all about List Comprehension. You can practice with a simple task in the above question itself to store the marks of 5 subjects comma- separated, instead of space separated.

Python 3.8 has provided an opportunity to try experimenting with List Comprehension using Walrus Operator. Let’s try something with walrus here. Now, you have seen that List Comprehension is a powerful technique and a bit hard to write. And walrus is more difficult to read and write. So, it’s a caution that, please don’t use these two concepts unnecessarily. It’ll make your code very cumbersome to interpret if used non-intelligently.

# Write a program using List Comprehension to separate zeroes present in any string using walrus operator. 

For the sake of understanding, let’s code it without using walrus operator and even without using list comprehension as well.

What we have done is, taken an empty list, result, in which we will store the final list after removing zeros from our input string. Checking for numbers present in our input string, if the number is not equal to zero, we’ll append that number in empty list, result. And the loop will go on executing, till all the values of input string have been checked. And then, the result will be printed. 

Now using List Comprehension the code will look like, “I want integer values of number for each number present in the data but if that number is not equal to zero.”

You might have understood comprehension to self-interpret the code. Let’s write the same code using a walrus operator. The difference will be that we don’t need to write the result variable beforehand. We can declare, assign and use it in run-time.

# Write a program using List Comprehension to calculate the average of marks given and display the grade using walrus operator.

We have computed this code earlier. Using the same concept, let’s write it down using a walrus operator now.

The first three lines are the same. In the 4th line of code, we have declare, initialize and assign values to the average variable. We have used the len() function to calculate the length of the marks list, which in this case is 5, because there are 5 subjects. And in elif condition, the average variable can be used also. So, we have saved a few lines I guess. Let’s see the result.

Working effectively. But, remember one thing. After writing the last mark, like here, it is 96; don’t give a space in a hurry before pressing enter. Or an error will occur and you’ll keep wondering what happened. For learning purposes, I am showing you the error.

This happened because I pressed the space bar after writing the last number. What if I give a few more marks? Will the average include all those marks or it’ll consider only first 5 marks or will it throw an error. That’s a task to check for you. (Hint: The formula of average holds the key of the correct answer.)

Before concluding List, let’s see how to convert a list to a string.

A list can be converted into a string by using ‘’.join (). Two quotes with or without space as required, a dot operator and then join () function. This operation sticks together all the strings presents in the list and return them as a single string.

That’s without space between quotes. Let’s insert one space.

That’s more readable. We can also use comprehension here. “I want string values of n for each value of n present in the string and then join these obtained string values of n together separated by a single space.

Another important concept is about Nested Lists, i.e., list within a list. Let’s see an example.

A list within a list is written by writing it in square bracket. It will give the index position to the entire bracket now and not the single element. Like in above example, index position zero is not the value 4, but [4,3,2,1] To access a specific value within a nested list, we have to first type the index position of the list and then the index position of value to be accessed. Like here when we type [0][2], it will go to the first index and within this list it will go to the 2nd index position.

It’s good enough here to end our discussion with lists.

Design a site like this with WordPress.com
Get started