Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Leverage `enumerate()`

00:00 Currently, the output of using the enumerate() function is not entirely what we want. The index starts with zero and we get the complete content of the positions list, but actually, we only want to have the three first positions.

00:14 That’s the part that I want to tackle. Next, I want to slice the list for only taking the first three positions, and I can do that by using the square brackets behind the positions variable that I pass into the enumerate() function and write :3.

00:35 And that makes sure that I only get the items of the list until index three, but not including index three. So I get index zero, one, and two, which are three items, and that’s what we want here.

00:48 So let’s see if that’s actually true by saving and running the module. And you can see now we get only three items back. Cool. So that’s the first part, which is nice.

01:01 But you may have wondered why do I actually want this index very well in there? I may have not mentioned this before, but I was thinking of the keys of the winner’s dictionary already.

01:12 So I want to refer to the winner’s dictionary by the keys to add the spaceship name as a value. Where currently the value is unknown. We want the spaceship names and to connect them, I want to use the index variable and the winners’ keys, but currently, they’re a bit out of sync.

01:33 My keys in the winners’ dictionary are 1, 2, 3, and the index variable values are 0, 1, 2. So that means I basically need to increment them. So I could either go into the for loop body and say, index = index + 1 or something like that.

01:52 But you can actually use another argument for the enumerate() function, and that’s the starting parameter.

02:01 Before passing in positions, you can say 1,. So start with an index one instead of by default an index zero. And then you pass in the iterable.

02:13 When you save and run the module,

02:18 we get a type error because the list object cannot be interpreted as an integer. That means probably I put the one in the wrong place of the enumerate() function call.

02:29 And instead of putting it at the beginning, you need to put it as a second argument. Let’s try that. So it’s positions, then square brackets, :3,, and then 1.

02:45 Let’s try it again. Save and run the module.

02:49 And then you can see it’s one defiant, two old Bessie, and three enterprise.

02:55 And that’s again, a good step in the right direction. We’re not there yet by adding the first three positions into the winners’ dictionary. Let’s save this step for the next lesson.

Become a Member to join the conversation.