Refactor to Use a for Loop
00:00 In a different lesson, I wrote some code that allows me to get three different nouns out of the nouns list. But if you look at this, you may see that there’s a lot of repetition in here.
00:09 So that doesn’t look clean or nice. And since you can see that we’re just doing the same thing over again, this usually is a good reason to use a loop. So I’m going to refactor this piece of code that’s working as I want it to into a loop.
00:25 I want to do this three times. I want to get three nouns out of the list, so I can iterate over a range object. And I don’t really need the loop variable here.
00:34 Something that you can do in Python is just assign the loop variable to an underscore. This kind of signifies that, yeah, you’re going to use a loop variable, but you’re not going do anything with it in the loop.
00:45 But it’s the same as saying something like throwaway variable or any sort of name that you want to put. It’s just shorter to write and has some sort of convention to it.
00:56
So other people that write Python code are going to understand that. So I will say for _ in range(3):
So I want to do this three times. I want to run the loop three times, and then I want to pick out a noun,
01:11 and then I want to remove it from the nouns list. Okay? And that immediately gets me rid of all of those things.
01:22
Of course, now I don’t have noun one through three, so I need to also collect them somewhere. I’m going to create a new nouns list, start it off as an empty list, and then after removing them, I’m going to append to this new nouns list, nouns.append(noun)
.
01:42 If your alarm bells are ringing now when you see this, you’re probably right, because I have nouns up here, and then I’m redefining nouns as an empty list.
01:52 So to me, that looks like a bug in the making, but let’s give it a try.
02:01
Well, I also need to print something now. print(nouns)
.
02:11 Hmm. Looks like my output is actually what I’d want it to be, but considering that I’m overriding the reference to nouns with an empty list, I was expecting a different result.
02:21 Oh, I see. I know what’s going on here. Maybe you see it too. I’ll give you a chance to take a look for yourself and investigate what’s happening and why this actually works fine.
02:30 Then we’ll unravel the situation together in the next lesson.
Become a Member to join the conversation.