1

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?

  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Nov 23 '22 at 11:48
  • Flatten the list first! See answer from `Kev` @ https://stackoverflow.com/questions/2158395/flatten-an-irregular-arbitrarily-nested-list-of-lists/4590652 – Rolf of Saxony Nov 23 '22 at 16:48

2 Answers2

3

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
oskros
  • 3,101
  • 2
  • 9
  • 28
-1

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()

lemmgua
  • 47
  • 4
  • `.isnumeric()` only works for strings, so it is not really relevant in the case of checking for ints and floats - additionally it doesn't solve the issue where you have a list within a list, as the question asks about – oskros Nov 23 '22 at 11:54