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

Exclude zero list elements in Python

I have a list km2. I am performing a list operation and generating a new list Time. However, I am getting an error because of the 0 element. I present the expected output.

km2=[0, 2.8945617583603203e-05, 0, 2.8964584076162397e-05, 2.8807838358146397e-05, 2.884599889020239e-05, 2.8869540930559196e-05]

Time=[-1/i for i in km2]
print(Time)

The error is

in <listcomp>
    Time=[-1/i for i in km2]

ZeroDivisionError: division by zero

The expected output 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

[0, -34547.54410099265, 0, -34524.92179312844, -34712.77461251153, -34666.85289028602, -34638.58335694811]

>Solution :

Handle 0 separately with a conditional expression:

Time = [-1/i if i != 0 else 0 for i in km2]

Alternatively, since 0 is considered falsy, != 0 can be omitted:

Time = [-1/i if i else 0 for i in km2]
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