Delete elements from a list which are less than tolerance value in Python

Question:

I have a list A. I want to probe each element of A such that if any element is less than tol, it should be deleted.

But, I am getting an error. I also present the expected output.

A= [[9.16435586e-05], [0.000184193464], [9.28353239e-05], [2.22105075e-18]]
tol=1e-12

for i in range(0,len(A)):
    if(A[i]<tol):
        A=A[i]
    else:
        delete(A[i])

The error is :

in <module>
    if(A[i]<tol):

TypeError: '<' not supported between instances of 'list' and 'float'

The expected output is :

[[9.16435586e-05], [0.000184193464], [9.28353239e-05]]
Asked By: modishah123

||

Answers:

do this:

if A[i][0]<tol :

instead of

if(A[i]<tol)

A= [[9.16435586e-05], [0.000184193464], [9.28353239e-05], [2.22105075e-18]]

your values are nested lists you have to unpack them

There is also some syntax error in your code; there is no delete rather del is the command. Also it is not advisable to delete items when iterating over them.

Edit:

You can get the desired output by:

[[x[0]] for x in A if x[0]>tol]
#[[9.16435586e-05], [0.000184193464], [9.28353239e-05]]
Answered By: God Is One

The error message says that you are trying to compare a ‘list’ with a ‘float’ as A is a list of list as defined in your code.

So you need to compare the first element of each sublist with the tolerance value.

The following code works.

A= [[9.16435586e-05], [0.000184193464], [9.28353239e-05], [2.22105075e-18]]
tol=1e-12

result = []
for i in range(0,len(A)):
    if(A[i][0] >= tol):
        result.append(A[i])

A = result

print(A)

Hope this help!

Answered By: tmc
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.