Possible Duplicate:
How to avoid returning a Null if there is no “else” condition in an If contruct
I have several situations where I need to conditionally add an element to a list, at various locations in the list. When the condition is not met, I want to add nothing at all, but the only techniques I can come up with result in the insertion of some element. For example
{1, 2, If[False, 3, Null], 4, 5, If[False, 6, {}]}
produces
{1, 2, Null, 4, 5, {}}
which is in many contexts thus contains elements that are invalid, e.g., here for functions that expect integers.
I understand that I could use Insert, but that quickly results in hard to parse code, where the positions of the conditional elements no longer corresponds to their position in the list construction code
If[True, Insert[#, 6, 6], #] &@If[True, Insert[#, 3, 3], #] &@{1, 2, 4, 5}
and which, in any case, produces errors without additional length checks:
If[True, Insert[#, 6, 6], #] &@If[False, Insert[#, 3, 3], #] &@{1, 2, 4, 5}
Insert::ins: "Cannot insert at position {6} in {1,2,4,5}"
Is there a form that will allow me to place conditional insertions of items in lists at the position where those insertions are to be made within the original list?
{1, 2, If[False, 3, Unevaluated@Sequence[]], 4, 5}– sebhofer Nov 03 '12 at 19:08