I have a list:
list={{{1},{2},{1,2},{1,2,3},{},{}},{{2},{3},{}}}
I would like to remove the empty lists {} to get:
{{{1},{2},{1,2},{1,2,3}},{{2},{3}}}
How can I automate this using Mathematica ?
I have a list:
list={{{1},{2},{1,2},{1,2,3},{},{}},{{2},{3},{}}}
I would like to remove the empty lists {} to get:
{{{1},{2},{1,2},{1,2,3}},{{2},{3}}}
How can I automate this using Mathematica ?
Using ReplaceAll (which can also be written /.) we can replace all the empty lists { } with Nothing.
list /. {} -> Nothing
{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}
Using DeleteCases:
list1 = {{{1}, {2}, {1, 2}, {1, 2, 3}, {}, {}}, {{2}, {3}, {}}};
DeleteCases[list1, {}, 2]
(*{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}*)
Considering the @Nasser's observation, we can generalize this strategy introducing the depth of the array to apply it in more complicated cases, as I show below:
DeleteCases[#, {}, Depth@#] &@list1
(*{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}*)
list2 = {{{1}, {2}, {1, 2}, {1, 2, 3}, {}, {}}, {3, {{{2}, {3}, {}}}}};
DeleteCases[#, {}, Depth@#] &@list2
(*{{{1}, {2}, {1, 2}, {1, 2, 3}}, {3, {{{2}, {3}}}}}*)
Thanks to Nasser for this valuable observation.
Another way, as suggested by @AndreasLauschke is to put Infinity instead of 2:
DeleteCases[list1, {}, ∞]
(*{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}*)
list={{{1},{2},{1,2},{1,2,3},{},{}},{3,{{{2},{3},{}}}}}; then DeleteCases[list,{},2] does not remove the {}. Screen shot !Mathematica graphics
$\endgroup$
list = {{{1}, {2}, {1, 2}, {1, 2, 3}, {}, {}}, {{2}, {3}, {}}};
p = Position[{}] @ list;
{{1, 5}, {1, 6}, {2, 3}}
Delete[p] @ list
{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}
MapAt[Nothing, p] @ list
{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}
ReplacePart[p -> Nothing] @ list
{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}
ReplaceAt[_ :> Nothing, p] @ list
{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}
list //. {} -> Sequence[]
and
list //. {} :> Unevaluated[## &[]]
both give
{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}
list = {{{1}, {2}, {1, 2}, {1, 2, 3}, {}, {}}, {{2}, {3}, {}}}
Using SequenceCases
SequenceCases[#, {a_, {} ...} :> a] & /@ list
{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}