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?
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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With