pythontuples

How do I separate the int and str and store them in their respective tuple?


How do I separate and store the items of a tuple within a tuple to their respective (new) tuple?

The code below is what I'm working.

The output I want is:

unique_num = (45, 21, 10, 24, 2) unique_ words = ('foot', 'basket', 'hand', 'foot', 'hand')**

def unique_data_items(data):
    unique_num = ()
    unique_words = ()
    for items in data:
        for values in items:
            if values == int:
                unique_num= unique_num + values
            elif values == str :
                unique_words= unique_words + values

        return ((unique_words), (unique_num))


data = ((45, 'foot'), (21, 'basket'), (10, 'hand'), (24, 'foot'), (21, 'hand'))
print(unique_data_items(data))

I've tried to approach this in a different way, and it worked, but I want to know why this way isn't working.


Solution

  • The condition part in your innermost for loop, values == int or values == str, is not doing what you are thinking. To really check their type, use type(values) == int.

    Moreover, tuples are immutable and you cannot simply concatenate a tuple with integer or string values.

    Here's another way of solving this problem.

    data = ((45, 'foot'), (21, 'basket'), (10, 'hand'), (24, 'foot'), (21, 'hand'))
    unique_num = tuple(i[0] for i in data)
    unique_words = tuple(i[1] for i in data)
    
    print(unique_num)
    print(unique_words)