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

前端 未结 9 1835
盖世英雄少女心
盖世英雄少女心 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:50

    You can also use type() if you want to exclude subclasses. See the difference between isinstance() and type():

    >>> not any(not type(y) is int for y in [1, 2, 3])
    True
    >>> not any(not type(y) == int for y in [1, 'a', 2.3])
    False
    

    Although you may not want to, because this will be more fragile. If y changes its type to a subclass of int, this code will break, whereas isinstance() will still work.

    It's OK to use is because there is only one in memory, so they should return the same identity if they are the same type.

提交回复
热议问题