# What is the correct way to conditionally add elements to lists? [duplicate]

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?

-

## marked as duplicate by Mr.Wizard♦Dec 12 '12 at 19:16

Try {1, 2, If[False, 3, Unevaluated@Sequence[]], 4, 5} –  sebhofer Nov 3 '12 at 19:08

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

-

This is the more normal approach:

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


{1, 2, 4, 5}

-

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}

-