Generating a list of numbers that are not multiples of 4

Why not:

Drop[Range @ 100, {4, -1, 4}]

Or:

Range[Range@3, 100, 4] ~Flatten~ {2, 1}

A couple general approaches:

Table[If[Mod[i, 4] != 0, i, Unevaluated@Sequence[]], {i, 100}]

Reap[Do[If[Mod[i, 4] != 0, Sow[i]], {i, 100}]][[2, 1]]

Note that the Unevaluated@Sequence[] thing is not a beginner's trick...Table always creates an entry for each iteration, so skipping some of them turns out to be tricky. Reap and Sow are one standard way to create table entries conditionally.


Update 1: @garej's answer reminded me that in V10 Nothing is an alternative to Unevaluated@Sequence[]:

Table[If[Mod[i, 4] != 0, i, Nothing], {i, 100}]

Update 2: In the comments that it is pointed out that Divisible[i, 4] is faster than Mod[i, 4] != 4. So if speed is an issue, one might consider using it for this specific type of problem. However, Divisible[], Nothing, Reap[], Sow[], and Sequence[] are not compilable, so the whole approach is a poor one if speed on long lists, for which Table[] will try to compile its body, is an issue. One could either develop a compilable code for Table or use another approach even better adapted to the special case of skipping multiples of an given integer.

n = 10^6;
d = 4;
Table[If[Divisible[i, d], Nothing, i], {i, n}]; //             (* not compilable *)
  RepeatedTiming // First
DeleteCases[Table[If[Mod[i, d] != 0, -1, i], {i, n}], -1]; //  (* compilable Table[] *)
  RepeatedTiming // First
Flatten@Outer[Plus, d * Range[0, n/d - 1], Range[d - 1]]; //   (* faster still *)
  RepeatedTiming // First
(*
  0.93
  0.26
  0.017
*)

If n is not divisible by d, then for the last method, one could generate a list that is slightly longer and trim it to the desired length with Part, Take or Drop; the extra processing would take a negligible amount of time.

Since the focus of the question seemed to be about how to translate C-like code that conditionally skips entries in a table, I thought a general answer would be most helpful. There may be faster approaches than Outer[Plus,..], the search for which I will leave to others. The timings were given merely to illustrate my claims about compilability.

If you are interested in speed, I would point out Mr.Wizard's Drop method which is faster than Outer, or the Floor method in my other answer, which is a little faster still.


If you see Select, you may try Cases.

DeleteCases[Range[100], x_ /; Mod[x, 4] == 0]

If you see Table, you may try Array:

Array[If[Mod[#, 4] == 0, Nothing, #] &, 100]

One more method with Table:

Complement[Range[100], Table[i, {i, 0, 100, 4}]]

To make PackedArray, one may also use:

Partition[Range[100], 4][[;; , ;; 3]]//Flatten

or

Delete[List /@ Range[100][[4 ;; 100 ;; 4]]][Range[100]]