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

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

    Combining some of the answers already given, using a combination of map(), type() and set() provides a imho rather readable answer. Assuming the limitation of not checking for type polymorphisms is ok. Also not the most computationally efficient answer, but it allows to easily check whether all elements are of the same type.

    # To check whether all elements in a list are integers
    set(map(type, [1,2,3])) == {int}
    # To check whether all elements are of the same type
    len(set(map(type, [1,2,3]))) == 1
    

提交回复
热议问题