# Using If statements internal to Table [duplicate]

Is there a way to use If statements with Table? To give a kind of ridiculous example that captures to spirit of what I'm trying to do, and I'm aware there are much better ways to do this, let's say we want to make an array of even values from zero to ten:

Table[If[Mod[k,2]==0,k],{k,0,10}]


The output is:

{0, Null, 2, Null, 4, Null, 6, Null, 8, Null, 10}


We could then delete the NULL entries and have our list of even values from zero to ten. However, how is this actually properly so that we don't have any NULL statements in the output from Table?

-

## marked as duplicate by Kuba, m_goldberg, Yves Klett, bobthechemist, gpapApr 3 '14 at 15:55

@Kuba Right, that looks like the same question to me. Should I do anything? – Bob2Alice Apr 3 '14 at 12:57
Not necessarily, it will be a sign for future visitors. – Kuba Apr 3 '14 at 13:02

You can do this :-

Table[If[Mod[k, 2] == 0, k, ## &[]], {k, 0, 10}]


{0, 2, 4, 6, 8, 10}

-
That certainly did the trick. Could you explain the syntax a bit? "## &[]" there's no way I would have figured this out on my own. – Bob2Alice Apr 3 '14 at 12:35
Here is a reference: vanishing function – Chris Degnen Apr 3 '14 at 12:38
Great, thanks for the reference, I'll be able to figure it out from there. – Bob2Alice Apr 3 '14 at 12:39
@Bob2Alice Perhaps Table[If[Mod[k, 2] == 0, k, Unevaluated@Sequence[]], {k, 0, 10}] is clearer. – Szabolcs Apr 3 '14 at 14:42

For variety's sake (and because I like Sow and Reap)...

Reap[Do[If[Mod[k, 2] == 0, Sow[k]], {k, 0, 10}]][[2, 1]]

-

There are many alternatives to If in Mathematica. One that you might use is rule replacement:

Table[Mod[k, 2] /. {0 -> k, _ -> Sequence[]}, {k, 0, 10}]

{0, 2, 4, 6, 8, 10}


Another is that you might write your own function that does exactly what you want, because Mathematica's Hold-related attributes allow you to write many control structures as if they were ordinary functions:

Attributes[when] = HoldRest;

when[True, value_] := value;
when[False, _] = Sequence[];

Table[when[Mod[k, 2] == 0, k], {k, 0, 10}]

{0, 2, 4, 6, 8, 10}

-