In the last lesson, you created two scripts where, in the end, you learned why they are not ideal to solve the issue of counting the seasons, And now it’s time to see how the
enumerate() function solves those problems and makes writing code a little bit more clean.
So let’s get started. Here again, we are in VS Code and I create a new file with the
code command. Depending on the editor that you are in, you have to create a file a little bit different, but also call the file
function. All right, again, I paste the
seasons list. If you haven’t saved it in your clipboard, just go back to the files that you create in the last lesson, or type the
seasons variable again.
And as you will see in a second, you will do basically two steps in one with the
enumerate() function. So in the last lesson you either used the
season variable, or you used the
count variable when you looped through the seasons or the range of the length of the seasons. This time, you can do both at once,
for count and
season in—and here it comes!—
And if you run the code again, then you have exactly the output that you wanted to have. So there is a bit happening here. This was a quite fast run-through, so let’s investigate a little bit what’s happening here with the
Maybe you already experienced while writing the code that it’s much more clean and concise compared to the other both scripts that you created. The other advantage is you don’t have to access any variables outside of the
You’re not accessing some variable, like in the
plus_one example, that is outside of it that you’re counting up or like in the
range_len example that you have to access the index of a list inside of the
So in summary, the advantage of the
enumerate() function is that it’s clean and concise and that using it, you’re creating a
for loop that is self-contained, but there are a few things happening under the hood. In the next lesson, you will find out what’s happening there.
Become a Member to join the conversation.