[MUSIC]
So you've seen many of the things that you can do with lists.
In this lecture, however, we're going to look at some examples so
you can see concretely different ways in which you can use lists.
And most importantly, I'm going to show you iteration.
Iteration is the operation on lists that allows you to step
through the list element by element, and
actually do something to each element if you'd like, all right.
This is where lists really get their powers.
So hopefully, by seeing this in action,
you're going to have a better understanding of how this is operating,
how you can use list in your programs.
So let's get started.
Okay, so here I am with a simple skeleton of a program here.
We're going to get, take a list of numbers,
and we're going to look at odd numbers in that list.
Okay, so first thing.
I've got my list of numbers and I'm going to print them out.
Okay, we already know how that works.
Great, I've got the list over here in the console.
So now, let's try to count the number of odd numbers, okay.
All right, so I take a list of numbers as input, and
let's start a variable count at zero.
Now, I want to iterate over the list, so
I use for num in numbers, okay.
This allows me to go through all of the elements in the list number, okay.
And each element gets assigned to num one by one, okay?
And so I can say, if num modular 2 == 1,
okay that means it's odd, then let's increment the count.
And at the end, let's return the count, okay?
So, how do I check if it's odd?
Well, I divide it by two basically.
If I do num mod 2, I'm going to get zero or one, right?
If I divide it by two and there's no remainder, I get zero.
If I divide it by two and there is one as a remainder, I get one, right.
And if there's a remainder, then it's odd.
So if that happens, I increase the count by one, all right.
And each time through this for
loop, num is going to get the next element in the list.
So I'm going to actually check each element in the list if it's odd and
I'll increment the counter if it is, all right?
So let's check in my list of numbers here.
Let's print count_odd, and numbers, okay.
See how many numbers are odd.
There are seven odd numbers in my list, okay.
Now, I can do a bunch of other things.
Let's actually try and check if there are any odd numbers at all in the list, okay.
So we start with a Boolean flag here, okay.
And this is a common programming technique,
where I have a Boolean variable that tells me if something has happened or not.
So initially, I have not found any odd numbers so I set odd equal to false.
Now, I iterate over the number's list.