Reputation: 1561
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?
Upvotes: 17
Views: 38544
Reputation: 38564
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.
Upvotes: 27
Reputation: 3061
You've forgotten to use enumerate, you mean to do this:
for index,item in enumerate(outputList1) :
pass
Upvotes: 11