user3062149
user3062149

Reputation: 4443

Can't unpack tuples when tuple of tuples has single tuple. Why? Works with array of tuples

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

Upvotes: 0

Views: 180

Answers (1)

s0mbre
s0mbre

Reputation: 574

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

mytup = (([1,2,3],['a','b','c'],99),)

Upvotes: 1

Related Questions