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