Check if all elements of a list are of the same type

前端 未结 9 1792
盖世英雄少女心
盖世英雄少女心 2020-11-28 05:08

How can I check if the elements of a list are of the same type, without checking individually every element if possible?

For example, I would like to have a function

9条回答
  •  情深已故
    2020-11-28 05:56

    Using any(), no need to traverse whole list. Just break as soon as object which is not int or long is found:

    >>> not any(not isinstance(y,(int,long)) for y in [1,2,3])
    True
    >>> not any(not isinstance(y,(int,long)) for y in [1,'a',2,3])
    False
    

提交回复
热议问题