This is more to do with how Python works internally.
If I give you a list, as an example -
a = [5, 19, 17, 30]
We know that we can access a particular value at a given index easily using something like -
The above will give us
We can also do something like -
for item in a:
Based on how Python works internally, that particular
for loop, knows that what we want to do is check each value/element in that list
a, and print out that value.
However, something like the following -
for item in a:
will throw an error, just like you would have gotten in your code. In this case, Python does not know what
item does not exist as per Python.
a exists since
a is defined and stored somewhere in memory. But there is no underlying implementation in Python for it to figure out what
I am being vague here because this is somewhat related to some advanced Python concepts which we might not even learn through DataQuest, I think.
It is related to a concept called
Iterators in Python. Our list
a is iterable, that is we can iterate over it. That’s why
for item in a is possible.
item is in turn called an
Iterator which, as I mentioned, is an advanced concept related to Python.
item gets defined as an iterator, and based on that we can easily have that
But Python does not create an iterator like
item. Because that’s essentially mixing two Python operations - creating an iterator, and indexing. Which is really not possible at the same time because
Iterators don’t really “store” all the items from that list at one time. They have to iterate through it. This is just a very high-level overview of what they do.
So, you have to separate out the two steps.
If you are interested in learning a bit more about this, then I would suggest this resource as a decent starting point. If it seems confusing, then don’t worry. Just come back to it later as you get more and more comfortable with Python.