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.


3 Answers 3

Total@list1 /. {Plus[x_, Times[_, Null]] -> x}  (* 3 *)
Total@list2 /. {Plus[x_, Times[_, Null]] -> x}  (* 4 Null *)
  • $\begingroup$ Thanks! nice workaround!! Though I wish Mathematica had an option to set Total of [] to Null $\endgroup$ Sep 3, 2020 at 0:08
totalWnulls[x_List] := If[MatchQ[{Null ..}] @ x, Total[x], Total[x] /. Null -> 0]

totalWnulls @ list1
totalWnulls @ list2
4 Null

Alternatively, define a function with two argument patterns:

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

totalWnulls2 @ list1
totalWnulls2 @ list2
4 Null
  • $\begingroup$ Thanks. This works, though being a beginner user at Mathematica I find this solution harder to comprehend that the one posted by Alan $\endgroup$ 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.

  • $\begingroup$ 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 $\endgroup$ Sep 2, 2020 at 23:59
  • $\begingroup$ Good point. You are right. I updated my answer. $\endgroup$ Sep 4, 2020 at 1:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.