Home > Enterprise >  check if every element in tuple are same type [duplicate]
check if every element in tuple are same type [duplicate]

Time:09-27

I want a function that check if all the elements of the tuple are of the same type.

e.g. :

auto('red', 42, {1,2,3}) #return False

auto('red', "aa", "hgbnj") #return True

Thank you.

CodePudding user response:

you could use a set and map each value to a type

def auto(*values):
    return len(set(map(type, values))) == 1

CodePudding user response:

Use isinstance:

def auto(*tup):
    return all(isinstance(i, type(tup[0])) for i in tup)

Or:

def auto(*tup):
    return len(set(map(type, tup))) == 1

Example:

print(auto('red', "aa", "hgbnj"))

Output:

True

Example 2:

print(auto('red', 42, {1,2,3}))

Output:

False
  • Related