Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of lists and "Too many values to unpack"

Tags:

python

I'm trying to use the following code on a list of lists to create a new list of lists, whose new elements are a certain combination of elements from the lists inside the old list...if that makes any sense! Here is the code:

 for index, item in outputList1:
    outputList2 = outputList2.append(item[6:].extend(outputList1[index+1][6:]))

However, I get a "Too many values to unpack" error. I seem to even get the error with the following code:

    for index, item in outputList1:
       pass

What could I be doing wrong?

like image 396
Bitrex Avatar asked Aug 02 '10 08:08

Bitrex


2 Answers

You've forgotten to use enumerate, you mean to do this:

for index,item in enumerate(outputList1) :
  pass
like image 33
Andrew Avatar answered Oct 03 '22 11:10

Andrew


the for statement iterates over an iterable -- in the case of a list, it iterates over the contents, one by one, so in each iteration, one value is available.

When using for index, item in list: you are trying to unpack one value into two variables. This would work with for key, value in dict.items(): which iterates over the dicts keys/values in arbitrary order. Since you seem to want a numerical index, there exists a function enumerate() which gets the value of an iterable, as well as an index for it:

for index, item in enumerate(outputList1):
    pass

edit: since the title of your question mentions 'list of lists', I should point out that, when iterating over a list, unpacking into more than one variable will work if each list item is itself an iterable. For example:

list = [ ['a', 'b'], ['c', 'd'] ]
for item1, item2 in list:
    print item1, item2

This will output:

a b
c d

as expected. This works in a similar way that dicts do, only you can have two, three, or however many items in the contained lists.

like image 145
Carson Myers Avatar answered Oct 03 '22 11:10

Carson Myers