Using isinstance for a list of bools / ints

100 Views Asked by At

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
2

There are 2 best solutions below

0
Pedro Freitas Lopes On

Try using all in conjunction with isinstance, like this:

lst = [1, 2, 3]

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

print(result)
4
linux.manifest On

Perhaps maybe a class can be used in this case

This is probably the closest way to check within the isinstance function itself.

I tried implementing a similar logic of the sorted function, where sorted(x, key=lambda x:x[0])

class integer_valid:

    def __init__(self, tuple):

        """ Valid integer tuple """

def validator(int_tup):

    all_ints = True

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

    if all_ints:
        int_tup = integer_valid(int_tup)

    return int_tup

Outputs

int_tup_1 = (1,2,3)

print (isinstance(validator(int_tup_1), integer_valid)) # prints True

int_tup_2 = (1,'2',3)

print (isinstance(validator(int_tup_2), integer_valid)) # prints False

A single liner can also be used:

result = isinstance(
            integer_valid(int_tup) if all(isinstance(element, int)
            for element in int_tup) else int_tup,
        integer_valid)