0

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
apostofes
  • 2,959
  • 5
  • 16
  • 31
  • yes, that would always be a possibility, to do a separate check for ints, but I was looking for a way to have a list of int check with isinstance, and further use it with match-case – apostofes Oct 24 '22 at 01:13
  • No, such a thing does not exist within the runtime of Python, though at the type checker at the type hinting level it may work, e.g. `lst: list[int] = [1, 2, 3]`. Does not apply at runtime, however. – metatoaster Oct 24 '22 at 01:22

2 Answers2

3

Try using all in conjunction with isinstance, like this:

lst = [1, 2, 3]

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

print(result)
-1

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)