S. Gamgee S. Gamgee - 4 months ago 13
Python Question

Python - Identifying Extraneous Types within a List

Suppose I have a 2-Dimensional list representing a matrix of numerical values (No, I am not using numPy for this). The allowed types within this list fall under the category of numbers.Number. Supposing that I wish to isolate any non-numerical values within this list, such as strings, the only option that I can see is to examine each element individually and check if it is not an instance of number.Numbers:

from numbers import Number

def foo(matrix):
# Check for non-numeric elements in matrix
for row in matrix:
for element in row:
if not isinstance(element, Number):
raise ValueError('The Input Matrix contains a non-numeric value')
...


My question is: is there another way to examine the matrix as a whole without looking at each element? Does Python or one of its libraries have a built-in function for identifying extraneous elements within a list (of lists)? Or should I continue with the current example that I provided?

Answer

Try this:

print(any(not isinstance(x, Number) for row in matrix for x in row))

And in the function:

def foo(matrix):
    if any(not isinstance(x, Number) for row in matrix for x in row):
        raise ValueError('The Input Matrix contains a non-numeric value')
Comments