Search code examples
pythonpython-3.xsubtraction

Subtracting two lists preserving "None" elements


Is there a pythonic way of subtracting the elements of two lists when the corresponding elements in both lists are different from "None" and placing "None" in the opposite case?

Example:

a = [11, 20, 3, 14, 5]
b = [3, 7, None, None, 0]

a - b = [8, 13, None, None, 5]

Solution

  • Instead of using None, you could use a NaN, which is designed for exactly this sort of purpose. Using None makes operations that contain some arbitrary other value to return that arbitrary other value

    import math
    a = [11, 20, 3, 14, 5]
    b = [3, 7, float('nan'), float('nan'), 0]
    c= b[3]-a[1]
    print(c)
    
    Result = "nan"