Iterating Without enumerate()
I will use VS Code for my coding, so when I’m writing code and then a filename—in this case,
plus_one.py—VS Code either opens the
plus_one file or creates a new one if it doesn’t exist. In this case, it doesn’t exist yet, so once I hit Enter, it opens up a new file. It has the dot because it’s not saved yet, so if I’m saving it, it’s there.
and you give it the value
count is an integer that keeps track of how far into the list you are, so if you print the
count variable as well, and you run the file again, you see for now, it’s staying with
1 because you’re not increasing it, so you also want to increase the
count variable every time you’re stepping over it.
But of course, depending on the editor you are using, you can use a different command to open and create your file. If you have copied the
seasons variable from the
plus_one file, you can just paste it here or write it again in line 3, so you have
stop parameter is the
len() (length) of the
seasons variable. So the length of
seasons is four, so you are looping four times and getting the
count variable value back in each step. To see what this is, you can print
So if you’re running the file
python3 range_len.py, then you will see that
count starts with
3, and now to also get the content of the
seasons list, you can access its index because the count is actually the index of
seasons that you want to access.
Let’s run it again to see what it is. So the
0 index of
Winter. This looks almost as you want it to be, but you have a problem here. You’re starting with
0, so you have to increase the
count variable for the
print() statement so it starts with
1. When you run it again, then you have exactly the print that you wanted to.
Now you have a look at the problems of the two scripts you just created. The first one,
plus_one.py, is a script that every one of us has written at some time, and I mean, we just did it in this lesson.
And the first thing that’s not ideal is that you declare the
count variable outside of the
for loop, and you refer to it always inside of the
for loop. So it’s outside of the scope where you actually do the work, so where you have the
Then, you must not forget to increment the
count variable, and more so, you have to increment it after the
print() statement. If you will increment it before the
print() statement, then you would start with
3 Summer, and so on.
There is this there’s one line with all the parenthesese—
range(len(seasons))—and then you have a similar problem like you had before, with the
count variable. But this time you’re referring to the
seasons variable outside of it.
Become a Member to join the conversation.