List Comprehension - BEST Python feature !!! Fast and Efficient

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone today we will talk about one of the best and coolest features of python the list comprehension and yeah best and coolest is a bit subjective but folks list comprehensions will absolutely change your life here's how so first what exactly is a list comprehension in some programming languages we have the ability to construct a list from another existing list well this doesn't sound very cool but what if i told you that we can take all those lines of code containing a for loop an if statement an else statement as well as the appending of modified content into a new list and we can narrow it down into a single beautiful line of code with the help of list comprehensions and this without using the append method even once so this folks is the true power of list comprehensions but that's not all we can also use them to customize strings and apply a different set of rules on different characters so in this tutorial we will explore all the benefits of list comprehensions in the realm of for loops conditional statements as well as string manipulation so let's begin with the very first example of how to convert a basic for loop into a list comprehension so here we have a list of fruits and we print each of its items one at a time now if we'd like to do the same with list comprehensions we will simply open a set of square brackets where we first specify the print command so print fruit followed by for fruit in fruits and that's it list comprehension is officially complete so essentially both techniques are using the exact same components in both cases we have the four keyword we also have the iteration variable fruit which we could have called f or i or whatever your heart desires it's entirely up to us we also have the in keyword followed by the name of the list and lastly we have the body of the for loop or the actions which we'd like to perform on all the list items now this particular example is very basic we're not really modifying anything we're just printing some output but what if we'd like to convert those lowercase fruit names into uppercase so let's do this together i have replicated the example we've just seen and you can copy this code from the description but if you don't feel like typing along with me you can always clone the complete version of my code from wayscript which is the ide or coding interface i'm using and the link is once again in the description so the first thing we will do is we will replace this print statement with fruit.upper where the upper method converts our string into uppercase or capital letters awesome now let's see what happens if we simply reassign this expression back to fruit do you think this will do the trick let's find out so at the very bottom of our code we will also print our list of fruits let's save everything and let's see if our conversion actually took place let's look at the results no this didn't happen this is not the way to convert our list items so what we usually do is we create an empty list at the top of our code let's call it fruit actually let's call it new fruits that makes sense and we will assign it to an empty set of square brackets then we will insert each of our modified list items into this new list by using the append method so we will type new fruits dot append to which we will pass our iteration variable fruit and keep in mind that we have already modified it in the line of code above and then the last thing left to do is we will reassign fruits to new fruits and this will basically replace the original array original list awesome let's save everything i'm still confused from the numpy tutorial let's run it and let's verify that i'm correct yep there you go here's our uppercase fruits but actually did we really have to go through all this process did we really need to create this empty list and then reassign it back to the originalist not even to mention that this time we are working with three list items so everything happens very fast but what if our list of fruits have thousands or millions of items how much time do you think it will take us to append all of them and with that in mind let's do the same with list comprehensions for this we'll simply delete everything because we don't need it anymore and we will then open a set of square brackets where we will convert each of our fruits into fruit dot upper and we will do this for every instance of fruit in fruits boom that's it we will then simply reassign it back to fruits let's print it below just to make sure this magic worked let's save it let's run it let's have a look and beautiful look at this it worked we have successfully modified the original array with a single line of code so let's quickly process what just happened here so first of all we never had to manually create a new list because list comprehensions automatically creates it for us that's why we always begin with a set of square brackets now another important detail is that the append method is notorious for being time consuming and since we didn't use it here even once this means that list comprehensions are always faster now let's say we have a list of boolean values and it represents bits which are the smallest units of logic in a computer system now we can choose how to denote them we can either do this with ones or zeros with on or off or in the case of our next example with true or false so let's say that this true or false implementation is not really gonna work for us maybe we are planning to do some math on those bits so it kind of makes more sense to represent them with ones and zeros and first let's do it the old way so we will enlarge my font we will then create a new list called new bits and we will assign it to an empty set of square brackets then we will iterate over each of our bits one at a time with for b in bits and the first thing we'll do inside the body of this for loop is add a conditional statement so if b equals equals true then we will append the integer 1 into our new list of bits so we will type new bits dot append and we will pass 1. now if this is not the case and b equals false we will need an else clause where we will do something very similar so let's just copy our previous line of code and we will then append the integer 0 into our list of new bits then at the very end of our code let's print bits alongside new bits just so we can see the difference between the two let's run it let's have a look beautiful we have replaced every instance of false with zero and every instance of true with one but we also know that if we are using a list comprehension we can do it much faster and much more efficiently so for this i actually want you guys to compare between the two so i'm leaving this for loop here and for our list comprehension we will open a set of square brackets where we first specify 1 if b equals equals true which corresponds to our if statement from above next we will add the else clause very very simply we'll just add else zero so if b equals true we replace it with one otherwise we replace it with zero and we will do the same for every instance of b in bits awesome now let's go ahead and assign it to a different uh type of list this time let's call it super bits it's not very logical but whatever okay let's save everything let's run it and we can verify that our new bits are an exact match to our super bits and our super bits were created in just a fraction of the time now this time we will see an example of string manipulation so we will begin with a very messy string in pascal case or upper camel case which basically means that it has no spaces and an uppercase character indicates the beginning of a ward so our goal here is to manually add some space characters in front of every word and then store the result back to my string and since this time we are dealing with a string rather than a list let's first see how a list comprehension will affect it so we will open a set of square brackets where we will type i for i in my string which means that we're not making any changes to the original string because i remains i awesome now let's reassign it back to my string and of course let's print it below let's save it let's run it let's look at it and oh my god what is this suddenly each of our characters is a separate item in a list well how can this be even useful now very often when we use list comprehensions on strings we also combine it with a join method just so we can connect all the characters back in place and that's exactly what we'll do so in front of our list comprehension we will specify an empty string followed by dot join and we will wrap our entire comprehension in a set of round brackets beautiful now if we rerun everything now it's much much better and we can officially make some changes within our list comprehension so let's modify the original string and my apologies in advance folks i'm going to break this one liner into several lines just for convenience purposes so we will replace the entire content of our list comprehension with i if i dot is lower so if our character i is lowercase we do not touch it we leave it as is however if it's not the case we will add an else clause where we will concatenate a space character in front of i beautiful and we will do this of course for all instances of i in my string let's save it let's run it beautiful look at this lovely string now the only problem is we now are adding a space character in front of the first word which is fine but i'm very picky so let's get rid of it and the fastest way to do so is to slice it off so in the end of our join method we will open a set of square brackets where we will keep all the items starting from the item at index 1 up until the very end which will basically remove the item at index 0 away from our string let's save it let's run it beautiful we no longer have the space character at index 0. now if we'd like to be extra picky we can also add an elsif clause in between our else clause and our if clause but the tricky part is we cannot use the elsif keyword inside a list comprehension so instead we use a special instance of the else keyword so unlike an else statement where we simply specify some kind of an action in an else if statement we specify the action followed by a condition so what do i mean so let's say we'd like to replace the capital n and the capital i of our string with a lowercase character this while still concatenating a space in front of it because we are once again dealing with new words so it kind of makes sense to separate them from one another now in this case our action will be concatenating and space character right in front of a lowercase instance of i which is given to us by i dot lower and then in terms of the condition we would like to select ends and i's they're capital instances so we will type if i can be found in a list with a capital n and a capital i okay let's save it let's run it beautiful now we are customizing our string even further and folks as far as i'm concerned you can even replace a bunch of characters with banana it doesn't matter it really doesn't because the key note here is that we are the true masters of our strings and yeah next time we talk please refer to my banana name and that's it we have just covered three major use cases of list comprehensions and we will of course practice our new set of skills in the upcoming tutorials now keep in mind folks that python also offers dictionary comprehensions and if you're curious to find out how it works please leave me a comment below now thank you guys so much for watching i really hope you learned lots of new things today and if you did please share this video with the world and don't forget to give it a huge thumbs up now if you'd like to see more tutorials of the exact same kind please subscribe to my channel and turn on the notification bell and last but not least if you have anything to say even if it's just hi maria please leave me a comment below i'm reading all of them even if i didn't have a chance to reply it doesn't mean that i didn't read it so yeah i'll see you very soon in a brand new tutorial so for now bye bye
Info
Channel: Python Simplified
Views: 188,759
Rating: undefined out of 5
Keywords: list comprehension, list comprehensions, list comprahensions, comprahensions, comprihensions, list comprihensions
Id: SNq4C988FjU
Channel Id: undefined
Length: 14min 51sec (891 seconds)
Published: Fri Jul 01 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.