Loading video player…

While Loops and Lists

In this lesson you’ll learn how to iterate over a list using a while-loop. The code is debugged in a live session in the video. A simple example may look like this:

Python
a = ["fizz", "baz", "buzz"]
while a:
    print(a.pop(-1))

00:00 All right. Now let’s see how we can use a list to iterate over a while loop. The first thing we need to do is declare a variable. I’m just going to say a is equal to a list containing three words, ['fizz', 'baz', 'buzz'].

00:24 Now, one thing to note. Whenever we evaluate a list in a Boolean context, it is going to return True if there’s any elements inside of that list.

00:34 So as long as this list has those things inside of it, it’s going to return True. But once that list becomes empty, it should return False. All right. So let’s now write our while loop.

00:46 So because of what I just said, we can actually say while a: and then that will iterate over our while loop. So for this block of code, I’m just going to print the result of performing the .pop() method on a.

01:07 This is just going to take off the last element of my list. So, take a minute to think about what the output is going to be and how many times I’m going to iterate over this code. All right, let’s look.

01:25 Okay. So what we see is we have buzz, then baz, then fizz. And if we look at our variables, we see that a is now empty.

01:33 Let’s use our debugger and walk it through it step-by-step. So first, we see our list and I am setting my variable a and I have my full list over to the side. So now whenever I go to iterate through my code, as long as there is something in this list, it’s going to return True.

01:59 So I should be able to iterate over my code.

02:08 And so we see I’m going to print('buzz'), and that’s that first bit. Now notice that this list has now two things in it, because that’s what the .pop() method does—it just takes something out.

02:20 So now I’m going to run that second list, the one that only has two things inside of it, and I’ll see what happens there. I’ll notice that I now printed 'baz', and all that’s left is 'fizz'.

02:34 So if I run this one more time, I now have an empty list. And if that’s the case, this is going to return False, and so my code is not going to be executed. And you’ll notice that it now broke out of my while loop. In the next video, we’re going to be looking at how we can actually break out of a loop prematurely.

Become a Member to join the conversation.