2

I don't understand why this works:

a = [(1,2)]
for x, y in a:
    print x, y

And this doesn't:

a = ((1,2))
for x, y in a:
    print x, y

I believe what happens in the first case is we create an iterator that returns a single value, (1,2). That tuple is unpacked, assigning 1 to x and 2 to y.

In the second, why doesn't the exact same thing happen?

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • possible duplicate of [Why do tuples with only one element get converted to strings?](http://stackoverflow.com/questions/12876177/why-do-tuples-with-only-one-element-get-converted-to-strings) – vaultah Jan 20 '15 at 03:55

1 Answers1

8

a = ((1,2)) is a single tuple of 2 elements - the ()s around it do nothing - it's the same as a = (1,2), to create a 1-tuple, you need a trailing comma, eg: a = ((1,2),) which is a 1-tuple containing a 2-tuple.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280