Home > Enterprise >  Using isinstance for a list of bools / ints
Using isinstance for a list of bools / ints

Time:10-24

I have a list of ints,

lst = [1, 2, 3]

how do I do a isinstance on this, to return True only for a list of ints?

isinstance(lst, list[int]) # does not work

CodePudding user response:

Try using all in conjunction with isinstance, like this:

lst = [1, 2, 3]

list = all(isinstance(x, int) for x in lst)

print(list)

CodePudding user response:

Perhaps maybe a class can somehow be used in this case

class integer_valid:

    def __init__(self, tuple):

        """ Valid integer tuple """

def validator(int_list):

    all_ints = True

    for element in int_list:
        if not isinstance(element, int):
            all_ints = False

    if all_ints:
        int_list = integer_valid(int_list)

    return int_list

Outputs

int_list_1 = (1,2,3)

print (isinstance(validator(int_list_1), integer_valid)) # returns True

int_list_2 = (1,'2',3)

print (isinstance(validator(int_list_2), integer_valid)) # returns False
  • Related