Try using all
in conjunction with isinstance
:
all(isinstance(x, int) for x in lst)
You can even check for multiple types with isinstance
if that is desireable:
all(isinstance(x, (int, long)) for x in lst)
Not that this will pick up inherited classes as well. e.g.:
class MyInt(int):
pass
print(isinstance(MyInt('3'),int)) #True
If you need to restrict yourself to just integers, you could use all(type(x) is int for x in lst)
. But that is a VERY rare scenario.
A fun function you could write with this is one which would return the type of the first element in a sequence if all the other elements are the same type:
def homogeneous_type(seq):
iseq = iter(seq)
first_type = type(next(iseq))
return first_type if all( (type(x) is first_type) for x in iseq ) else False
This will work for any arbitrary iterable, but it will consume "iterators" in the process.
Another fun function in the same vein which returns the set of common bases:
import inspect
def common_bases(seq):
iseq = iter(seq)
bases = set(inspect.getmro(type(next(iseq))))
for item in iseq:
bases = bases.intersection(inspect.getmro(type(item)))
if not bases:
break
return bases
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…