tags:

views:

88

answers:

2

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?

+2  A: 

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

for index,item in enumerate(outputList1) :
  pass
Amoss
Whoops, so I did! Thanks!
Bitrex
+1  A: 

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.

Carson Myers
That is not how iteration over a dict works. Try it in a terminal and you'll get blah is not iterable, where blah is the class of the key. What you are thinking of is for key,value in dict.items(): but that is not default behaviour as you've said.
Amoss
you're right, I'll update the question
Carson Myers