Consider the following code:

Sum[If[b != 0, a[m], 0], {m, 1, 4}]

(* 4 If[b != 0, a[m], 0] *)

Why does it return me a[m]? m is the index of the summation, it shouldn't appear in the result.

Here I expect to have:

If[b != 0, a[1], 0]+If[b != 0, a[2], 0]+If[b != 0, a[3], 0]+If[b != 0, a[4], 0]

I don't understand this behavior

(my example here is to understand this behavior, my specific problem is more complicated but the problem is the same as this one showed here).


2 Answers 2


This works:

Sum[If[b != 0, a[m] // Evaluate, 0], {m, 1, 4}]

From the documentation:

If evaluates only the argument determined by the value of the condition.

$ $

You can use Evaluate to override HoldFirst etc. attributes of built-in functions.  


The other answer by Andrew technically answers your question, but, maybe what you really wanted was

Sum[If[b =!= 0, a[m], 0], {m, 1, 4}]

which returns

a[1] + a[2] + a[3] + a[4]  

The difference between the != and =!= operators is very important here. Because the truth value of b != 0 could not be determined, therefore the If[] expressions were returned unevaluated.

I suggest moving the If[] expression out of the summation. That is use

If[b =!= 0, Sum[a[m], {m, 1, 4}], 0]

instead. This simplifies the code and makes it easier to understand.


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.