Understanding "ValueError: need more than 1 value to unpack" w/without enumerate()

2.2k views Asked by At

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.

2

There are 2 answers

4
caleb531 On

If you were to actually print out the result of the enumerate() function as a list:

print(list(enumerate(["a","b","c","d"])))

You would see this:

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Therefore, if you wanted to print the index and item at that index using enumerate(), you could technically write this:

for pair in enumerate(mylist):
    print pair[0], pair[1]

However, that's not the best (i.e. Pythonic) way of doing things. Python lets you write the above much more nicely like so:

for index, item in enumerate(mylist):
    print index, item

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

4
Ignacio Vazquez-Abrams On

If indexes are a part of the structure of a list...

Except they aren't. Not when you iterate over the list. The indexing becomes a matter of time/occurrence, and they are no longer associated with the elements themselves.