I've been searching around for a succinct explanation of what's going on "under the hood" for the following, but no luck so far.
Why, when you try the following:
mylist = ["a","b","c","d"]
for index, item in mylist:
print item
I get this error:
ValueError: need more than 1 value to unpack
But when I try:
for item in mylist:
print item
This is returned:
a
b
c
d
If indexes are a part of the structure of a list, why can't I print them out along with the items?
I understand the solution to this is to use enumerate()
, but I'm curious about why iterating through lists (without using enumerate()
) works this way and returns that ValueError
.
I think what I'm not understanding is: if you can find items in a list by using their index (such as the case with item = L[index]
) — doesn't that mean that one some level, indexes are an inherent part of a list as a data structure? Or is item = L[index]
really just a way to get Python to count the items in a list using indexes (starting at 0 obviously)? In other words, item = L[index]
is "applying" indexes to the items in the list, starting at 0.