Fix the Bug
00:00 The last lesson, I successfully finished creating this script, and it works as expected. However, I also mentioned that there is an intentionally built-in issue that maybe you discovered, maybe not.
The error that you’re getting is
IndexError: list index out
of range, and it is related to the mutability of lists. What you’re doing in here is popping elements off the list or removing them from the list, right?
01:16 You may access them with different references, but they’re still the same objects. So you are removing and popping from these lists, which means that eventually there’s not going to be enough items in there to give you the selection that you’re trying to get inside of your script, right?
01:42 So what you need is to make a deep copy of those lists instead of just using these objects in there. Then every time you’re going to work with a different list and the items that you pop off or that you remove don’t really matter in the next run of the loop, because there’s going to be a fresh new list, okay?
Create a deep copy of the words to pull. Because I’m creating a deep copy, it’s actually also going to create copies of all the lists in there, which is exactly what you want, because you want to have a new list for each time that you’re calling
make_poem(). Does it work? Give it a run.
02:47 though the spacing is a little off, but you actually get ten poems that start with the title, and then a space, and then the actual poem. Okay. Just as a little reminder that this mutability of lists is a very cool thing.
03:02 You know all of the things that you’ve done in here, basically by shuffling the list, for example, you can only do with lists because they’re mutable, but they also have this downside to it, which is that you need to be aware of what’s the object you’re actually working with.
03:15 And in this example, are you depleting the object? So make sure that you have an actual copy that you’re working with in a situation like that, and then you’re not going to run into any troubles.
Become a Member to join the conversation.