7
votes

Let's say you have a list of lists and that you wish to delete only those lists with the length zero, something like:

a={{...},{...},{...},...}
DeleteCases[a, ?]

What should the ? be?

2
This question has been asked here at SO before in a slightly more general formulation: stackoverflow.com/questions/6562902/… - Leonid Shifrin

2 Answers

11
votes
In[1]:= a={{1,2,3},{4,{5,5.5},{}},{},6,f,f[7],{8}}
Out[1]= {{1,2,3},{4,{5,5.5},{}},{},6,f,f[7],{8}}

Here's the solution that Nasser provided:

In[2]:= DeleteCases[a, x_/;Length[x]==0]
Out[2]= {{1,2,3},{4,{5,5.5},{}},f[7],{8}}

Note that it deletes all objects of length zero at level 1. If you only want to delete lists of length zero (i.e. {}) from the first level then you can use

In[3]:= DeleteCases[a, {}]
Out[3]= {{1,2,3},{4,{5,5.5},{}},6,f,f[7],{8}}

or if you want to delete them from all levels then use ReplaceAll (/.)

In[4]:= a /. {} -> Sequence[]
Out[4]= {{1,2,3},{4,{5,5.5}},6,f,f[7],{8}}
5
votes

may be this:

a = {{1, 2, 3}, {4, 5}, {}, {5}}
b = DeleteCases[a, x_ /; Length[x] == 0]


{{1, 2, 3}, {4, 5}, {5}}