'How to avoid failing with Decimal function when 0/0 occurs?

I have a Python 2.7 script and it uses two lists and divides the numbers to each other then creates a new list with the results and it is working fine but it errors on the line below anytime the script has to divide 0 / 0, which happens sometimes depending on the state of my current servers. Is there any way to avoid this?

complist =[a, b, c]
totallist=[d, e, f]

percentlist = [Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)] 

I am getting error:

    MacBook-Pro-3$ python dailyReport.py 
    Traceback (most recent call last):
  File "dailyReport.py", line 67, in <module>
    percentlist = [Decimal(l) / Decimal(t) * 100 for l,t in zip(complist, totallist)] 
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 1321, in __truediv__
    return context._raise_error(DivisionUndefined, '0 / 0')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 3873, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: 0 / 0


Solution 1:[1]

How about

percentlist = [0 if t == 0 else Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)]

Solution 2:[2]

I went to https://www.REPL.IT and tried your code. Generally, I don't Think python allows division by ZERO. I tried your code and print(0/0), and it returns an error

Solution 3:[3]

use try and except

try:
    complist =[a, b, c]
    totallist=[d, e, f]

    percentlist = [Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)]

except decimal.InvalidOperation:
    print 'divide by zero error'

EDIT

If you want to add it in new list use that.

newlist = []
try:
    complist =[a, b, c]
    totallist=[d, e, f]

    percentlist = [Decimal(c) / Decimal(t) * 100 for c,t in zip(complist, totallist)]

except decimal.InvalidOperation:
    newlist.append(0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aguy
Solution 2 Michael Ilie
Solution 3 Hammad