2
$\begingroup$

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.

$\endgroup$
1
$\begingroup$
Total@list1 /. {Plus[x_, Times[_, Null]] -> x}  (* 3 *)
Total@list2 /. {Plus[x_, Times[_, Null]] -> x}  (* 4 Null *)
$\endgroup$
1
  • $\begingroup$ Thanks! nice workaround!! Though I wish Mathematica had an option to set Total of [] to Null $\endgroup$ – mariodrumblue Sep 3 '20 at 0:08
1
$\begingroup$
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
$\endgroup$
1
  • $\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$ – mariodrumblue Sep 3 '20 at 0:10
0
$\begingroup$

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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