The previous thread suggested an efficient way to remove empty lists ( {} ) from lists:
Replace[expr, x_List :> DeleteCases[x, {}], {0, Infinity}]
Using the in-place Trott-Strzebonski evaluation method , this method can be generalized to work with held expressions:
f1[expr_] := Replace[expr, x_List :> With[{eval = DeleteCases[x, {}]}, eval /; True], {0, Infinity}]
This solution is more efficient than the ReplaceRepeated based ReplaceRepeated :
f2[expr_] := expr
But it has one drawback: it evaluates held expressions if they are wrapped in a List :
In[20]:= f1[Hold[{{}, 1 + 1}]] Out[20]= Hold[{2}]
So my question is: what is the most efficient way to remove all empty lists ( {} ) from lists without evaluating expressions? An empty List[] object should only be deleted if it is an element of another List .
Here are some timings:
In[76]:= expr = Tuples[Tuples[{{}, {}}, 3], 4]; First@Timing [
Definitions:
Clear[f1, f2, f3]; f3[expr_] := FixedPoint[ Function[e, Replace[e, {a___, {}, b___} :> {a, b}, {0, Infinity}]], expr]; f1[expr_] := Replace[expr, x_List :> With[{eval = DeleteCases[x, {}]}, eval /; True], {0, Infinity}]; f2[expr_] := expr