Heyyy, how is it going? I hope you guys are doing great and are finding our articles helpful J Welcome to another lesson, today we will be learning about list comprehensions. You will definitely find this concept very useful and it is in fact quite interesting. So, let us get straight to it !!
WHAT IS A LIST COMPREHENSION? HOW IS IT USEFUL?
List comprehension allows you to create lists based on criteria applied to existing lists. Basically, we are creating lists out of existing lists based on a condition. Let us say we have a list of numbers. We can now create a list of odd numbers out of that list of numbers. In order to do that, we will iterate through the list and check if the numbers in the list are even or odd. If they are even, the loop will continue to the next number and not do anything. If the number is odd, that number will be added to the new list and so on.
Let us try to understand this with an example:
my_nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
This is our list of numbers that we will be iterating through and looking for the odd numbers. We will use the following line of code to iterate through the list and add only the odd numbers to a new list.
new_list = [num for num in my_nums if num % 2 != 0]
In the above line of code, we are going through the list with our basic for loop while also specifying the condition for the elements in the new list. The for loop goes through each number and the if statement checks if the current value of ‘num’ is odd. If it is, that number is added to the new list and if it isn’t the loop continues.
Now our new list of numbers will look like this:
[1, 3, 5, 7, 9]
LIST COMPREHENSIONS FROM STRINGS:
You can even use this method to create lists from strings. It is the exact same process. You will be iterating through the string and applying the criteria to each element in the string.
For example:
input_string = ‘Buy 1 Get 2 Free’
This will be our input string for this example. Now let us say we need to extract the last number from this string and store that number in a new list. As we can see, there are two numbers in this string ‘1’ and ‘2’. We need the new list to store ‘2’ as the only element. We can do this with the following statement:
last_number = [c for c in input_string if c.isdigit()][-1]
Let us understand what is happening here. As explained in the first example, the for loop iterates through the string and the if statement checks if the current value of ‘c’ is a digit or not. If ‘c’ is a digit, it is added to the list, otherwise the loop continues. After the loop iterates through the string whilst adding the numbers from the string to the new list, our new list should look like this:
[‘1’, ‘2’]
Since, we only need the last number, we will use -1 as the index value to refer to that last element.
Now, the variable last_number stores the number ‘2’.
OTHER APPLICATIONS:
It doesn’t end here. You can actually use this method to create a modulated version of the actual list. The general syntax of creating a list comprehension looks like this:
[expression(i) for i in input_list if filter(i)]
We know we can use this syntax to create a new list from an existing list. But let us try something new!
Let us say we have the following list of numbers:
my_nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
We have already learnt to create a new list of odd numbers out of this list. But let us now create a list that stores thrice the value of odd numbers in this list. So, if ‘1’ is the odd number we are looking at, our new list will store 1 * 3 i.e. ‘3’. Similarly, if the number is ‘3’, the list will store ‘9’ as its element.
We can do so in the following way:
new_list = [c*3 for c in my_nums if c % 2 != 0]
This is what our new list will look like after the execution of the above statement:
[3, 9, 15, 21, 27]
And this is not it, you can do a lot of stuff with this method. Another example is if you want to create a list that contains the first letter of every word in the string you can use the following expression:
[word[0] for word in input_string .split()]
The split() function will create a list of words used in the sentence. If split() is not used, Python will iterate through each element in the list instead of iterating through each word.
CONCLUSION:
The applications are endless. Try to solve some problems with this, and see how efficient your program becomes. Instead of running a separate for loop and writing lines of code to apply your condition to the list and then adding the element that fulfills the criteria to a new list, you can use this one line to keep your program short and simple.
Did this method help you make your program more efficient? You can share your opinion with me in the comments below. If this article helped you, consider leaving a like, I would really appreciate it ;)If you have any queries regarding the topics taught in this lesson or previous lessons, you can always find me in the comments section, in the telegram channel or on my Pinterest profile where you can personally talk to me and ask me questions about anything we have learnt so far.
Stay tuned for another article next week,
same time, where we will discuss about a new topic/concept in programming,
what they are, how they work and where you use them. More cool stuff
coming your way, DON’T MISS IT !! And I'll see you next week. Goodbye and Good
Luck :)
I hope this article answered all of
your questions and even helped you in becoming a better programmer. FOLLOW
NOOB CODE PRO TO BECOME A PROFESSIONAL PYTHON PROGRAMMER FROM A TOTAL BEGINNER. Feel free
to ask any further queries in the comment section below.
If you are a beginner, intermediate, advanced or just someone interested
in programming, feel free to join our telegram channel and be among people like
you:
https://t.me/joinchat/AAAAAFVduJs3bF00nwKGUA
And do you know the best part? Joining it is FREE !!!
So go ahead click on the link and I will see you there.
You can also contact me through my email: code2learnofficial@gmail.com
or
HOPE YOU HAVE AN AWESOME DAY AHEAD !!!
0 Comments
Welcome to the comments section, this is where you can contact me personally for any doubts or feedback