Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete sublists of size zero in Mathematica

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?

like image 843
liberias Avatar asked Aug 12 '11 23:08

liberias


2 Answers

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}}
like image 129
Simon Avatar answered Nov 20 '22 14:11

Simon


may be this:

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


{{1, 2, 3}, {4, 5}, {5}}
like image 38
Nasser Avatar answered Nov 20 '22 13:11

Nasser