7

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?

orome
  • 12,819
  • 3
  • 52
  • 100

3 Answers3

14

As @sebhofer suggested, you seem to be looking for Sequence,

{1, 2, If[False, 3, Unevaluated@Sequence[]], 4, 5}

A shorter verision that @Mr.Wizard likes using is

{1, 2, If[False, 3, ## &[]], 4, 5}

Both return what you want

{1, 2, 4, 5}

In any case, there are probably more efficient ways of accomplish this that are also easy to parse, so I suggest you give us an example and perhaps we can come up with better solutions

Rojo
  • 42,601
  • 7
  • 96
  • 188
4

This is the more normal approach:

DeleteCases[{1, 2, If[False, 3], 4, 5, If[False, 6]}, Null]

{1, 2, 4, 5}

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
1

You can create a pick list of True/False values for each element based on your selection function and then use Pick.

include = IncludeElement/@myData

{True, True, False, True, True, False}

Pick[Range@6, include]

{1, 2, 4, 5}

image_doctor
  • 10,234
  • 23
  • 40