In Mathematica one can do something like the following:

lst = {1, 2, 3};
If[Length[lst] != 0, Print["list is not empty"], 
 Print["list is empty"]]
(*list is not empty*)

Is there something relevant to automatic Boolean casting?

E.g., for L being a list

If[L,Print["list is not empty"], Print["list is empty"]]

would return list is not empty. That is, using the non-Boolean type with an If statement will cast the first to a Boolean.

As a second example

(*for n being an integer*)
If[n%2,Print["n is odd"],Print["n is even"]

would return n is odd for, e.g. 19.

  • 2
    $\begingroup$ I don't think this exists. AFAIK, there is not even an inverse of Boole, i.e., a built-in function that maps {0,1} to {False,True}. $\endgroup$
    – Felix
    Feb 27, 2017 at 21:00

2 Answers 2


here is how you can implement it yourself:

if[x_, y_, z_] := Module[{f, g},
Which[Head[x] === List,
(f = Length@x > 0; Switch[f, True, y, _, z]),
Head@x === Integer, (g = Mod[x, 2]; Switch[g, 1, y, _, z])]


if[{}, "list is not empty", "list is empty"]

(* "list is empty" *)

if[{1, 2, 3}, "list is not empty", "list is empty"]

(* "list is not empty" *)

if[20, "n is odd", "n is even"]

(* "n is even" *)

if[19, "n is odd", "n is even"]

(* "n is odd" *)
  • 1
    $\begingroup$ Thank you very much for your workaround! $\endgroup$
    – Dimitris
    Feb 28, 2017 at 10:55

I don't think this is a good idea, but if you really want to you can easily redefine If

If[0, _, b_] := b
If[_?NumericQ, a_, _] := a

If[0, Print["a"], Print["b"]]
(* b *)

If[1, Print["a"], Print["b"]]
(* a *)

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.