Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a specific type of tuple or list?

Suppose,

var = ('x', 3)

How to check if a variable is a tuple with only two elements, first being a type str and the other a type int in python? Can we do this using only one check? I want to avoid this -

if isinstance(var, tuple):
    if isinstance (var[0], str) and (var[1], int):
         return True
return False
like image 649
yashu_seth Avatar asked Sep 24 '15 20:09

yashu_seth


2 Answers

Here's a simple one-liner:

isinstance(v, tuple) and list(map(type, v)) == [str, int]

Try it out:

>>> def check(v):
        return isinstance(v, tuple) and list(map(type, v)) == [str, int]
...
>>> check(0)
False
>>> check(('x', 3, 4))
False
>>> check((3, 4))
False
>>> check(['x', 3])
False
>>> check(('x', 3))
True
like image 196
ekhumoro Avatar answered Sep 28 '22 09:09

ekhumoro


Well considering tuples are variable in length you're not going to find a method that checks this instance of all it's types. What's wrong with the method you have? It's clear what it does and it fits your usage. You're not going to find a pretty one liner AFAIK.

And you do have a one liner... Technically:

def isMyTuple(my_tuple):
    return isinstance(my_tuple,(tuple, list)) and isinstance(my_tuple[0],str) and isinstance(my_tuple[1],int)

var = ('x', 3)

print isMyTuple(var)

If you're going to do this check many times, calling the method is DRY!

like image 35
visc Avatar answered Sep 28 '22 09:09

visc