7

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?

Simon
  • 14,631
  • 4
  • 41
  • 101
liberias
  • 235
  • 1
  • 6
  • 4
    This question has been asked here at SO before in a slightly more general formulation: http://stackoverflow.com/questions/6562902/efficient-way-to-remove-empty-lists-from-lists/ – Leonid Shifrin Aug 13 '11 at 14:51

2 Answers2

11
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}}
Simon
  • 14,631
  • 4
  • 41
  • 101
  • good point about non-lists items at first level. I did not think about that since the example shown has all lists at first level. But it is good you pointed out this. – Nasser Aug 13 '11 at 01:11
  • Thanks @Nasser. It probably isn't an issue in liberias's problem, but I thought it was worth mentioning. – Simon Aug 13 '11 at 01:36
  • 2
    Just beware of `Sequence[]`, [it could swallow you hole](http://www.imdb.com/title/tt0289605/) – Dr. belisarius Aug 13 '11 at 01:54
  • 1
    @belisarius would not that be preferable to being swallowed in half? (If there is a serious caveat to `Sequence[]` I missed your point.) – Mr.Wizard Aug 13 '11 at 23:31
  • @Mr. That was a joke, of course. Everybody knows that `Sequence[]` is just the sound of one hand clapping. – Dr. belisarius Aug 13 '11 at 23:40
5

may be this:

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


{{1, 2, 3}, {4, 5}, {5}}
Nasser
  • 12,849
  • 6
  • 52
  • 104
  • Thanks a lot! (I rarely use mathematica...) – liberias Aug 12 '11 at 23:39
  • 7
    @Nasser It would quite a bit be more efficient to do `DeleteCases[a, {}]`. E.g. `a = Range /@ RandomInteger[{0, 5}, 10^6];` Then your variant runs in 1.2 seconds, while `DeleteCases[a,{}]` only takes 0.15 seconds. – Sasha Aug 13 '11 at 14:06
  • Thanks, that is good to know. Mathematica is somewhat complicated because there is always many ways to do the same thing. Finding the correct way to do something can be hard enough, finding the correct and also the most efficient way can be even harder. But it is always interesting to try to find how many ways one can do the same thing in Mathematica. – Nasser Aug 13 '11 at 15:45