0

I was just curious about this and thought this should logically work in python. I tried the following code in the python console:

mylist = [('a','b'),('c','d')]

for i,x,y in enumerate(mylist):
    print i,x,y

ValueError: need more than 2 values to unpack

But if I try to not enumerate and just do the following:

mylist = [('a','b'),('c','d')]

    for i,x in mylist:
        print i,x

it works fine. I was just wondering why the first method doesn't work as that shouldn't really hinder python unpacking values from tuples should it? Unless I have overlooked something embarrassingly simple. I'd really like to know the reason for this peculiar behavior.

How to generate enumerated tuples from a dictionary with a list comprehension in Python?

says that the value of enumerate() function is a two element tuple. But in my case the second element of the tuple returned by enumerate would itself be a tuple so why can it not be unpacked?

Community
  • 1
  • 1
anonuser0428
  • 11,789
  • 22
  • 63
  • 86
  • Might help: http://stackoverflow.com/questions/849369/how-do-i-enumerate-over-a-list-of-tuples-in-python – alecxe Jan 10 '14 at 00:48
  • It also might help to just do `for z in enumerate(mylist): print(z)` and see what you're getting. – abarnert Jan 10 '14 at 00:50
  • ya I understand that in the first case it's a tuple of an index and another tuple but I just felt that since in the second case, without the enumerate, it unpacks the tuple on its own. In the first case with the enumerate it would recursively unpack the tuple inside the enumerate tuple. No big deal was just curious about this behavior. Thanks for all your responses. – anonuser0428 Jan 10 '14 at 00:52

3 Answers3

2

each entry from enumerate returns exactly 2 values; the first is the enumeration; the second is the next in the input list.

I think what you mean is the following:

for i,(x,y) in enumerate(mylist):
    print i,x,y
AMADANON Inc.
  • 5,753
  • 21
  • 31
1

The first method doesn't work because that's not how they're packed.

for i, (x, y) in enumerate(mylist):
    print i, x, y
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

When you iterate over mylist, each value is an item: a tuple of two strings.

When you iterate over enumerate(mylist), each value is a tuple of an index and an item, which is itself a tuple of two strings. So, you're effectively doing this:

i, x, y = (0, ('a', 'b'))

That won't work. But this will:

i, (x, y) = (0, ('a', 'b'))

And therefore, what you want is:

for i, (x, y) in enumerate(mylist):
abarnert
  • 354,177
  • 51
  • 601
  • 671