Reputation: 1443
How can I check if a variable is a list of tuples?
isinstance only reveals if a variable is a list or a tuple, but I don't know how to check nested structures.
Upvotes: 3
Views: 3125
Reputation: 104092
Use all
>>> lit=[(1,),(2,),(3,)]
>>> lin=[(1,),(2,),(3,),4]
>>> all(isinstance(e,tuple) for e in lit)
True
>>> all(isinstance(e,tuple) for e in lin)
False
You can also negate a lambda in filter both to test and to find the elements that are not tuples:
>>> filter(lambda e: not isinstance(e, tuple), lit)
[]
>>> filter(lambda e: not isinstance(e, tuple), lin)
[4]
Or use a list comprehension to find the index of the non tuple:
>>> [i for i, e in enumerate(lit) if not isinstance(e, tuple)]
[]
>>> [i for i, e in enumerate(lin) if not isinstance(e, tuple)]
[3]
If you use filter
or a list comprehension, an empty list is also 'falsy' so that can both be a test and a result if you are looking for the actual elements that are not tuples.
Upvotes: 1
Reputation: 6151
You can use a combination of all
and instanceof
:
>>> a = [(1,2),(3,5)]
>>> all(isinstance(item, tuple) for item in a)
True
>>> b = [(1,2),(3,5), "string"]
>>> all(isinstance(item, tuple) for item in b)
False
>>>
Upvotes: 9