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 -
a[2]
The above will give us 17
.
We can also do something like -
for item in a:
print(item)
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[2] in a:
print(item)
will throw an error, just like you would have gotten in your code. In this case, Python does not know what item[2]
is. item[2]
does not exist as per Python. a[2]
exists since a
is defined and stored somewhere in memory. But there is no underlying implementation in Python for it to figure out what item[2]
is.
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.
That 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 for
loop.
But Python does not create an iterator like item[2]
. 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.