Hi, everyone.
Today we will talk about one of the best and coolest features of Python.
The list comprehension and yes the best and coolest
is a bit subjective, but folks - list comprehension
will absolutely change your life.
Here's how.
So first, what exactly is a list comprehension?
In some programing 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 and 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
pure full line of code with the help of list comprehension.
And this without using the append method even once.
So this folks, is the true power of list comprehension.
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 comprehension in the realm of for loops
conditional statements, as well as string manipulation.
So let's begin with a very first example
of how to convert a basic for loop into a list.
Comprehend again.
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 comprehension, we will simply open
a set of square brackets where we first specify the print command.
So print fruit, followed by four 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 key word.
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 N 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 way script,
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 dot 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 with 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 now.
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 make 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 that 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 number tutorial.
Let's run it and let's verify that I'm correct. Yup.
There you go. Here's our upper case 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 your original list?
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 comprehension.
For this, we will 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.
That's printed 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's 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 comprehension is automatically created 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 comprehension 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, which true or false.
So let's say that
this true or false implementation is not really going to 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 four B in bits.
And the first thing
we'll do inside the body of this for a loop is add a conditional statement.
So if B equals equals true,
then we will append to the integer one into our new list of bits.
So we will type new bits, dot append and we will pass one.
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 zero into our list of new bits.
Then at the very end of our code, let's sprint 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, in 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 one.
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 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 Monte population.
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 ward 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 awesome.
Now let's reassign it back to my string.
And of course, let's printed 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 comprehension.
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 ie 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 can cartoony a space character in front of us.
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 ward, 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 one up until the very end,
which will basically remove the item at index zero away from our string.
Let's save it. Let's run it. Beautiful.
We no longer have this space character at index zero.
Now, if we'd like to be extra picky, we can also add an elusive clause
in between our else clause in our if clause.
But the tricky part is we cannot use
the elusive keyword inside a list comprehension.
So instead we use a special instance of the keyword.
So unlike an L statement where we simply specify
some kind of an action in an elusive 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 PN
and the capital 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
in space character right in front of a lowercase
instance of I, which is given to us by either the lower.
And then in terms of the condition, we would like to select ends
and i's there capital instances.
So we will type if I can be found in a list
with a capital n in the capital I k let's save it.
Let's run it. Beautiful.
So now we are customizing our string even further.
And folks, as far as I'm concerned, you can ever 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 strengths.
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 comprehension 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 comprehension.
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.