Use a List Comprehension
00:09 You may know that if you’re doing some sort of loop where you’re just creating a list and appending to that list inside of your loop, then there’s a chance that you can replace it with a list comprehension.
00:20 And while the code that you wrote before doesn’t entirely work for that because you’re doing some sort of removal task in there, at least with the specific code that you’re using here, it’s not a great fit for list comprehension.
00:33 We could probably use some slightly different functions and methods to make that work. So I want to try that out. Now to do the three adjectives using a list comprehension, the basics of a list comprehension is you give it a name.
and start off with the open and close square brackets. And now in here, I want to start with the element that I want to add to the list in this case. And up here with
.remove(), that wouldn’t work out, but if you recall, there is a method that returns the element that you pick out of the list.
I need to call this method on a list object. And we have that list object for adjectives. We know it’s, it’s at
words index number two,
nouns is zero,
verbs is one,
adjectives is two,
words is a reference to my
And now I’m popping off the last element of that list. So this is what I want to do. It’s not entirely done yet, right? So we need to first finish this comprehension, and I’ll keep with the idea that I’m using up here for the number, like just the amount of times I want to do it by saying
for _ in range(3), I’m popping off three elements from the
02:06 However, currently, because I’m not passing any index in here, it’s always just going to get the final element. So that would mean that every run that I do, I’m going to get the same adjectives.
That’s not quite a solution yet because I want random ones, but we do have the list comprehension, so that’s kind of fun. To solve the random part, we’re going to again grab a function from the
random module, and it contains a function that’s called
shuffle() takes, let me see what IDLE says here.
03:31 Then I will pop out the last three elements from there. And so every time this gets shuffled, there’s going to be a different order. And then, so it’s fine that I just take the last three because there’s going to be different last three ones every time I run this.
You can see this is a different approach that I could have used for both of these
verbs situations. Before we have the exact same situation, I need to get three random words out of a list, and I want to make sure that it’s not the same ones up here.
I solved it with a
for loop and then
random.choice() and the
.remove() list method. And down here now I solved it with using
random.shuffle(), shuffling the list, and then using a list comprehension where I use
.pop() to pick off the final three elements of the shuffled list and assigning it then to the
Become a Member to join the conversation.