mardi 27 juillet 2021

#Tuple Unpacking- I dont Understand why - (TypeError: cannot unpack non-iterable int object) occurs

CODE:

list1 = [(1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11)]

for tup_obj in list1:
    if len(tup_obj) == 2:
        for a, b in tup_obj:
            print(a)
            print(b)
    elif len(tup_obj) == 3:
        for a, b, c in tup_obj:
            print(a)
            print(b)
            print(c)
    elif len(tup_obj) == 4:
        for a, b, c, d in tup_obj:
            print(a)
            print(b)
            print(c)
            print(d)

The think what i need to do is to unpack the tuples inside the list

list1 = [(1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11)]-this is the list which i need to unpack..this consist of tuples with different number of elements inside each tuple

so im trying to take each item in the list ((ie)nothing but the tuple)once it is selected i want to check how many elements are there inside that tuple..here in first case the number elements inside the tuple is 2 ...this i did with the help of in built len functions to count how many elements are there present in each tuple..so if its two im gonna take the value as a,b and if the selected tuple contains 3 or 4 elements means im gonna take the variable as a,b,c or a,b,c,d but once this step is completed its telling that cannot unpack non iterable int object ...but i dont know why?

Aucun commentaire:

Enregistrer un commentaire