12. For and while loops and list/dict comprehension in python
Oct 10, 2023
For loops in python are extremely powerful. Rather than index from start to stop with some incremented, it can do much more! It is able to iterate through any iterable object including lists, sets, tuples, dictionaries, and strings. We can also do list comprehension and dictionary comprehension to create sub-lists form a larger list given a logical condition. While loops are also possible in python if you don't know how long the loop will need to continue.
Let's talk about loops in Python.
Loops are something that are really useful
if you want to do a task over and over and over a set number of times,
or maybe until a different condition is met.
They're also really useful for iterating through sequential objects
like lists, dictionaries, tuples, sets, or strings even, right?
So loops, in most of the languages,
stick to something that looks like this,
for some sort of iterator in the range of you're going to start here
and you're going to go till there, and it'll usually say the iteration,
like you're going to increase by one each time.
And Python can do that, right?
So we can grab this little snippet of code.
Let's come over to Spyder, drop it in there, and this can work.
Let's clean it up a little bit so we get rid of the tabs, right?
There we go.
So for x in the range of 0 to 3, we're going to print we're on time,
and it's going to say which version of the iteration we're under.
When we run this, yeah, sure enough, it says we're on time 0,
we're on time 1, we're on time 2,
and since it goes up until 3, but not inclusive, right?
Like all slicing in Python, it starts here, but it doesn't include that one.
It did the first three iterations starting from index 0.
So that's what most other languages use when they're talking about for loops,
but in Python, you can do so much more than that, right?
So for example, we said that it can iterate through lists,
dictionaries, tuples, sets, and strings.
Let's do an example of that.
Let's make a list of our favorite music.
So we're going to call this list bands,
and it's going to be populated with all of the best bands.
Okay, we've got our list full of radical bands.
So now what can we do with this using loop stations?
Well, using loops in Python.
Well, we can do lots of really cool stuff.
The syntax for this is going to be really straightforward.
We're going to say for,
now we're going to say something that represents the items in the list,
but you don't have to name it like anything specific, right?
You can name it whatever you want.
We can call these like for rad bands in bands, right?
So for some sort of element in the iterable bands, right?
For rad bands and bands can iterate through them.
Let's just have it print out the name for one thing, right?
Let's have it print rad bands.
Rad bands is the item, and since it's already a string,
we can just send it just like that,
and it will print out the bands that are in our loop.
So this is pretty cool.
Let's run it, and sure enough,
we did our first three things from running from zero to three in our regular loop.
So that's these first three here,
but then it listed out all the names of the bands, right?
So that's pretty great.
It's a really simple way to iterate through these things, right?
We can also do something really cool.
We can use the enumerate command.
So we're going to do enumerate.
What enumerate command does is if you give it a string
and you apply the enumerate command to a string,
it not only pulls out the value at a string,
but it pulls out the index associated with it,
which means we're not just going to be pulling the string,
we're also going to be pulling a number representing the string.
So let's just write num, right?
So for the num representing the enumerate value and the rad bands,
let's go ahead and we'll say that rad bands,
and then we're going to put comma is band number,
and then we will have it give us the number, right?
So let's run that,
and it says Jimmy eat world is band number zero.
Pearl Jam is band number one.
And what's really cool is with the enumerate command,
you can actually have it start at a more normal number,
not like Python starting at zero.
You can over here under enumerate, you can put start equals one,
and that's an argument that it knows what to do with,
and it's going to now say that Jimmy world is band number one instead of zero.
So this is a really cool thing.
In the old days of writing your code,
this would have been a lot more work.
It would have been many more lines of code.
It's really convenient how Python allows us to work with for loops, okay?
So what else can we say about these?
The range function, if you are doing it the old school way,
from some iterator, from some number up to some higher number,
you don't have to count by ones.
You could count by something else, right?
For example, if we wanted to go from zero to 10 and count by fives,
great, we can do that.
And you'll notice that it counts zero, then five.
So that's possible to do, okay?
Okay, if you're using a for loop,
and you need to stop before the loop is complete,
you can use the break function.
So for example, let's say that we're doing this, okay?
Now, after some time, we'll say,
if rad bands equals, we're going to use the two equals,
that means we're doing a comparator, right?
If it's equal to shaky graves, right, colon, then we're going to break.
Like once it reaches shaky graves in the list,
it doesn't have to keep printing the names of the bands.
So let's run that.
And now we see that, sure enough, the same stuff from before,
but now it only did the first three bands,
Jimmy World, Pearl Jam, shaky graves.
And then it stopped because we did this break command.
So that's how you can exit out of the loop
before it would normally complete, okay?
You can use the continue statement.
So if you, for some reason, wanted to move on,
like if this equals shaky graves,
like let's move this down, actually, let's do this.
We'll move this below it.
So now we're going to put this right there.
So the first thing it's going to do is
it's going to check to see if you're on shaky graves.
Then if it's not, it's going to continue, right?
Otherwise, it's going to print the band number.
So let's try that.
Now, when you run it, you see it prints one, two,
but it does not print three because we told it to continue.
Basically, before it could finish this loop,
it skipped this line of code because we did the continue command
and it went to the next iteration,
which was band number four.
So it skipped printing out band three
and went straight to four because of that continue command.
You can do other stuff.
The else keyword is what will be executed
when you finish the loop entirely.
So down here, let's come down,
and we're going to do else down here.
Now, what do we want to do after we enumerate all the bands?
That's when we can then say, maybe we'll have it print.
We'll have it print.
There is no other good music.
Sorry, Generation Z with your Post Malones
and your mumble rapping.
That's it.
There is no other good music.
Okay.
You can do nested loops.
If you do a nested loop, what's going to happen
is it's going to go all the way through the loop on the inside
before it iterates the larger loop.
Let me show you an example of this.
All right.
So let's clear this out.
Well, let's do this over here.
We'll comment this one out for a moment.
So control one to comment that section out.
We're going to get rid of this if statement.
And instead, let's have it print some.
Well, first, we'll do another for loop.
So for, okay, this time we're going to do the letter, right?
So the letter in rad bands.
So now we're not going to go within the value band, right?
We're going to go letter by letter through this,
and we're going to spell it out.
Let's do that.
Okay.
So for the letter in rad bands, we're going to print.
Let's see.
We're going to print letter, and then we'll do a carriage return.
So that's backslash n.
Okay.
So that should put them all in different lines.
This is probably going to be big, but let's try that.
Okay.
We'll get rid of this thing.
Well, no, we'll leave that.
And then we'll say is a band number.
Okay.
So let's run that.
Okay.
So if you look there, it went through all of them,
all the way at the very top.
It started with Jimmy world and it, right on lap one,
it stepped in rad bands value was Jimmy eat world.
So now it's going letter by letter through rad bands,
and it's printing the letter plus a carriage return,
like an enter line, right?
So that put all these like that, Jimmy eat world.
And then when it got to the end of that,
it stepped out of this inner for loop.
It finished that inner for loop, and it came to this line.
It said the band is number one, right?
And then it came to our second one, which is Pearl Jam.
It did the exact same thing and so forth, right?
So you can do nested loops.
You can do as many as you want, right?
This is just two, but you could do as many as you want.
Okay.
You can do a pass statement inside a loop if it's empty, right?
So if for some reason you wrote a for loop,
but you didn't know what you wanted to put in there yet,
you need to put a pass, right?
Otherwise it will give you an error
if there's nothing inside of it.
Okay.
All right.
What else can we say about loops in Python, right?
Something really cool you can do is list comprehension.
List comprehension is a really fast way to create a new list
based off of specific values in an old list.
This is way faster than doing the regular for loop
is to do list comprehension.
Here's how the syntax works.
You have some new list.
The syntax needs to be some expression
for an item that is in the iterable,
and then you can add logic, like if some condition is true.
So let's do this.
Let's say we'll call this bands with i, right?
And what we want to do is we want to pull from this list up here
only the bands that have the letter i in them, right?
So we're going to do square brackets, right?
Because we're still dealing with the list.
So that's what the syntax says.
So we want to, again, what is our expression?
It's going to be a band.
So let's just call it x in x, right?
In iterable, or x for x, excuse me.
So the value is x for x in our iterable.
The iterable is our x for x in.
The iterable is bands.
If x, let's see, if, let's see, the letter i is in x.
Okay, let's try that.
So if that's the case, it's going to put them into a new list,
which is called bands with i.
So let's run it.
It's going to do the big old thing.
And now we have a list up here, a new one, bands with i.
And sure enough, it only has Jimmy World, David Bowie, and Dispatch,
because the other ones didn't have i in it.
So this is way faster than going through a loop
like you would normally do to create something like this.
And again, this is called list comprehension.
You'll see this used a lot in Python.
Also, it's kind of nice that it just crams it onto one line
instead of like this big chunky block of text.
This is exactly what you want it to do.
You're going to return something for something in that list of things
if some condition is met.
Pretty slick, right?
By the way, you can do this also with dictionaries, right?
Dictionary comprehension is also possible.
The only catch is that the syntax is a little bit different.
You have to have...
The new dictionary is going to be some returned key and value
for a key and a value in some iterable, right?
So let's try this out.
So this comes from my graduate student, Kai,
who taught this class last year.
I like this example, so we're going to do it.
He started with the list of the elements in order, right?
So this is going to start with hydrogen, right?
And then it goes to helium, right?
Then it goes to lithium.
After lithium, we have what?
Beryllium, then boron, carbon, nitrogen, then oxygen, right?
So we've got beryllium, then boron, then carbon, then nitrogen, and oxygen, right?
And we could keep on going, but this is fine for now.
So if we run it currently,
what we're going to see is there's this element list here, right?
Now, this is just a list and it has them in order.
But what would be great is if we could take this element
and use that to get the atomic number,
because we know that that is the atomic number, just plus one, right?
These values, if we added one to them, we would have an atomic number.
So let's create a dictionary where this is the key and this is the value, right?
The key is the name of the element,
and the value is going to be its atomic number.
And we're going to do that with dictionary comprehension.
So here's how it works.
We're going to say element dict, right?
So we're going to create a dictionary.
Now, we're going to use curly brackets because we're talking about a dictionary, right?
So what we're going to do is, remember our syntax,
we want the returned key and value.
So let's call this number and x, right?
For some key and value, right?
So we're going to say, so for some number, comma, and x, right?
Where x represents the element name.
Oh, by the way, since it's a dictionary, that needs to be a colon, right?
Doesn't it?
Also, we're going to return this value plus one
because we don't want the index to start at zero
because the atomic number doesn't start at zero.
It starts at one.
So that's going to increase it by one.
This is going to be in the iterable, which is our elements list.
But in order to get this value of this number,
we need to use the enumerate command,
which we've been using in this example earlier.
Let's try that.
See if it runs.
Okay, so it's got an error.
It says can only concatenate strings.
What is it not like here?
Ah, this needs to be i, right?
Okay, there we go.
x was the value of the string,
and we were trying to add a number to a string,
and that was giving us an error.
So now we run it.
i is not defined.
Oh, that's because we're calling it number.
Sorry, this is the value of the string.
So that is the key, is the value of the string.
Number is the number coming out of enumerate.
Okay, now it should work.
So we come over here to element dictionary,
and sure enough, now we have a dictionary
where hydrogen is number one.
Helium is atomic number two.
Lithium's three.
These are not in order because dictionaries are not ordered,
but the key thing is we can pull out any of these,
and it'll give us the right one.
So for example, we can come over here,
and we can type element dict,
and I can ask for the value of carbon, right?
And it will tell me the correct atomic number.
Six, right?
Which is right.
So that is how you can do list comprehension
on both lists and dictionaries, okay?
So list and dictionary comprehension.
Now the last thing we want to cover in this is while loops.
That's another type of loop you can do,
and this one is until a certain condition is met,
then that's the while loop.
So let's do an example.
Let's use the, let's create a variable called liar, right?
So we're going to call this currently true,
that somebody's a liar, right?
And we're going to do a while loop.
We're going to do a while loop.
While liar is equal to, we're doing two signs
because it's the comparison, right?
It's a logic operation.
While it's equal to true,
we're going to keep on doing this loop.
Now, what are we going to do inside this loop?
We're going to ask somebody's age, right?
So their age is equal to, we're going to do input.
Input is a special command that brings a string in from the user.
So we're going to ask them their age.
What's your age?
Okay, now there's a couple problems here.
First off, I did this right there.
That means I need a backslash in front of it
because that would normally be the end of our string.
Okay, so what's your age?
Also, this is coming in as a string, but age is an integer.
So let's turn that into an integer.
So we're just going to do integer of that.
Now, we're going to check whether or not
they gave us a crazy age or something realistic.
So we're going to say if age is greater than zero, right?
So it's going to throw out negative numbers.
Then we're going to assume that they're not lying anymore.
So we're going to say that liar is equal to false, okay?
So let's try and run this.
What we find is the normal stuff we did from before,
but now it's asking us what's our age.
Let's try putting in a number that's crazy.
Negative five.
You know what it did?
It just ran all the way through.
So it brought in that number for age.
It found out that it was negative five,
and then it checked.
It says, is that greater than zero?
And since it's not greater than zero,
then they still must be a liar.
And so while the liar condition is still true,
it's just going to keep on asking, right?
I could put in negative 10, put a negative 20.
It's not going to like it.
Oh, look, there's a mistake.
I put in something negative two,
then negative by accident.
It tried to convert that to an integer from a string,
and it didn't know what to do with that negative sign afterwards.
And so it failed.
So let's try this again.
This time we're going to put negative two,
but now we're going to put positive two.
And it ends.
It ends, no problem.
It left the while loop.
So that's how you can do a while loop
where maybe you don't know how long it's going to take
for the right answer to appear.
You can do a while loop until it appears.
Just make sure that eventually it will,
or you'll be stuck in an infinite loop,
and you'll have to break your program.
By the way, if this is ever running in an infinite program,
you can hit the stop sign,
and it will break your program in the middle,
and you can go back and figure out what went wrong.
So those are loops in Python.

