Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check to make sure all items in a list are of a certain type [duplicate]

Tags:

python

I want to enforce that all items in a list are of type x. What would be the best way to do this? Currently I am doing an assert like the following:

a = [1,2,3,4,5]
assert len(a) == len([i for i in a if isinstance(i, int)])

Where int is the type I'm trying to enforce here. Is there a better way to do this?

like image 940
samuelbrody1249 Avatar asked Sep 12 '20 03:09

samuelbrody1249


2 Answers

I think you are making it a little too complex. You can just use all():

a = [1,2,3,4,5]
assert all(isinstance(i, int) for i in a)

a = [1,2,3,4,5.5]
assert all(isinstance(i, int) for i in a)
# AssertionError
like image 187
Mark Avatar answered Oct 06 '22 09:10

Mark


You need to decide whether you are interested in also including any subclass of int. isinstance(i, int) will return True if i is True or False because bool is a subclass of int.

Whatever you do, you should certainly use all as Mark Meyer suggests. (And incidentally, one advantage of doing that over what you are doing with len is that if any fail the test then it doesn't needlessly check the remaining items, provided that you are using a generator and not building a list of results -- the fact that no [...] symbols used anywhere in the syntax gives a clue that this is the case.)

But if you are only interested in including actual int type itself, then you should do:

assert all(type(i) is int for i in a)

(If you do want to allow e.g. bool, then see Mark Meyer's answer.)

like image 43
alani Avatar answered Oct 06 '22 09:10

alani