Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]]

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading