0

Why can't a single tuple in an tuple of tuples be unpacked? A single tuple in any array of tuples does work, however.

Tuple of Tuples (many tups) --- Works

mytup=(([1,2,3],['a','b','c'],99),([2,2,3],['b','b','c'],100))
for t in mytup:
    z1,z2,z3=t
    print(z3)

Result:

99
100

Tuple of Tuples (single tup) --- Does not work

mytup=(([1,2,3],['a','b','c'],99))
for t in mytup:
    z1,z2,z3=t
    print(z3)

Result:

3
c
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-171-1c4755f1cb92> in <module>
     13 mytup=(([1,2,3],['a','b','c'],99)) #,([2,2,3],['b','b','c'],100))
     14 for t in mytup:
---> 15     z1,z2,z3=t
     16     print(z3)

TypeError: cannot unpack non-iterable int object

Array of Tuples --- Works

mytup=[([1,2,3],['a','b','c'],99)]
for t in mytup:
    z1,z2,z3=t
    print(z3)

Result:

99
user3062149
  • 4,173
  • 4
  • 17
  • 26
  • 2
    `(([1,2,3],['a','b','c'],99))` should be `(([1,2,3],['a','b','c'],99),)` the outer parentheses aren't treated as tuple are instead treated as parentheses that signify order – Primusa Sep 11 '19 at 03:10
  • Ah, forgot about that. So it does work with a tuple of tuples. I just defined my single tuple wrong. Thanks! – user3062149 Sep 11 '19 at 03:34

1 Answers1

1

Just place a comma before the last closing bracket to show it's a tuple:

mytup = (([1,2,3],['a','b','c'],99),)
s0mbre
  • 361
  • 2
  • 14