# How can I remove empty lists { } from a nested list?

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 ?

## 5 Answers

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}}}*)

• fyi, this does not work on general. It works for the input given. For example, if the input was list={{{1},{2},{1,2},{1,2,3},{},{}},{3,{{{2},{3},{}}}}}; then DeleteCases[list,{},2] does not remove the {}. Screen shot !Mathematica graphics Commented Dec 26, 2023 at 23:37
• Use Infinity instead of 2 Commented Dec 26, 2023 at 23:46
• @AndreasLauschke You're right, thanks for the suggestion. :-) Commented Dec 26, 2023 at 23:49
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}}}

• (+1) I hadn't seen the second one, nicely done mate! :-) Commented Dec 27, 2023 at 4:04
• @E.Chan-López thanks a lot! :-)
– bmf
Commented Dec 27, 2023 at 5:09
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}}}