pythontuples

Tuple iteration failed : TypeError: cannot unpack non-iterable int object


So I have a nested tuple and I try to run the code above but I have an error:

tup = (((1,2),(3,4),(5,6)))

for sub_tup in tup:    
    for (a,b) in sub_tup:
        print(a)

Do anyone can explain me what's happeing here? I get the error:

TypeError: cannot unpack non-iterable int object

If I do:

for (a,b) in tup:
   print(a)

I won't get the error.

I expect that I can use a nested for loop to acces a nested tuple but is not like that!


Solution

  • You need to remember the trailing comma for single-element tuples, otherwise they don't define a tuple and just act as no-op parentheses:

    tup = (((1,2),(3,4),(5,6)),)
    
    for sub_tup in tup:    
        for (a,b) in sub_tup:
            print(a)
    

    prints:

    1
    3
    5