Search code examples
pythonpython-2.7divide-by-zero

Ignoring zero by division instances in script


Is there a way to ignore values in a list that create a division by zero in an iterative script instead of removing those problem values?

I'm thinking along the lines of if

if(x==0):
 break
elif(x!=0):
 continue

Where the values that aren't zero get to continue on through the script.


Solution

  • You can use list comprehension for a more efficient code,

    from __future__ import division
    num = [1,2,3,4,5,6,3,31,1,0,120,0,0]
    divisor = 10
    print [divisor/x for x in num if x != 0]
    

    Output:

    [10.0, 5.0, 3.3333333333333335, 2.5, 2.0, 1.6666666666666667, 3.3333333333333335, 0.3225806451612903, 10.0, 0.08333333333333333]