# Ignore Null when summing elements of a list, but return Null if all elements are Null

Let's say I have two different lists for which I want to compute the total

list1 = {1, Null, 2, Null}
list2 = {Null, Null, Null, Null}


For list1, I want the total to be 3, i.e. ignore the Null elements and add the numeric ones. For list2, I want the total to be a Null since all elements are Null. I achieve want I want for list1 with

In[255]:= Total[DeleteCases[list1, Null]]

Out[255]= 3


However, the same command applied to list2 returns 0

In[254]:= Total[DeleteCases[list2, Null]]

Out[254]= 0


On the other hand, using only Total does not work with list1

In[256]:= Total[list1]

Out[256]= 3 + 2 Null


but works for list 2

In[257]:= Total[list2]

Out[257]= 4 Null


I'd like a command that works for both lists because the list might look like list1 or list2 depending on a parametrization.

Total@list1 /. {Plus[x_, Times[_, Null]] -> x}  (* 3 *)
Total@list2 /. {Plus[x_, Times[_, Null]] -> x}  (* 4 Null *)

• Thanks! nice workaround!! Though I wish Mathematica had an option to set Total of [] to Null Sep 3, 2020 at 0:08
ClearAll[totalWnulls]
totalWnulls[x_List] := If[MatchQ[{Null ..}] @ x, Total[x], Total[x] /. Null -> 0]

totalWnulls @ list1

3

totalWnulls @ list2

4 Null


Alternatively, define a function with two argument patterns:

ClearAll[totalWnulls2]
totalWnulls2[x : {Null ..}] := Total[x]
totalWnulls2[x_List] := Total[x] /. Null -> 0

totalWnulls2 @ list1

3

totalWnulls2 @ list2

4 Null

• Thanks. This works, though being a beginner user at Mathematica I find this solution harder to comprehend that the one posted by Alan Sep 3, 2020 at 0:10

One approach (which is not completely right as pointed out in the comments ) is

f[list_] := (Plus @@ list) /. Null -> 0


Better is:

f[list_] :=
If[MatchQ[list, {Null ..}], Null, Plus @@ list /. Null -> 0]


Null as a return value does not display on output.

• sorry but I don't think this works for list2. It still returns a 0 whereas I'd like the function to return Null if all elements are Null Sep 2, 2020 at 23:59
• Good point. You are right. I updated my answer. Sep 4, 2020 at 1:15