Home > Software design >  Check if a python list contains numeric data
Check if a python list contains numeric data

Time:11-23

I am checking whether a list in python contains only numeric data. For simple ints and floats I can use the following code:

if all(isinstance(x, (int, float)) for x in lstA):

If there any easy way to check whether another list is embedded in the first list also containing numeric data?

CodePudding user response:

You can do a recursive check for all lists within the list, like so

def is_all_numeric(lst):
    for elem in lst:
        if isinstance(elem, list):
            if not is_all_numeric(elem):
                return False
        elif not isinstance(elem, (int, float)):
            return False
    return True
print(is_all_numeric([1,2,3]))
>>> True

print(is_all_numeric([1,2,'a']))
>>> False

print(is_all_numeric([1,2,[1,2,3]]))
>>> True

print(is_all_numeric([1,2,[1,2,'a']]))
>>> False

CodePudding user response:

I don't know if there is another way to do this, but you could just do a for loop for each item, and if any of those items is not a number, just set on bool to false:

numbers = [1,2,3,4,5,6,7,8]

allListIsNumber = True

for i in numbers:
    if i.isnumeric() == False:
        allListIsNumber = False

You can either use isnumeric() or isinstance()

  • Related