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.
If you were to actually print out the result of the
enumerate()
function as a list:You would see this:
Therefore, if you wanted to print the index and item at that index using
enumerate()
, you could technically write this:However, that's not the best (i.e. Pythonic) way of doing things. Python lets you write the above much more nicely like so:
This works because when you use the
index, item
syntax, you are telling Python to "unpack" each pair in that list by treating the components of each pair separately.For more on how this tuple unpacking magic works, see: Tuple unpacking in for loops