14
$\begingroup$

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 ?

$\endgroup$
2

5 Answers 5

24
$\begingroup$

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}}}
$\endgroup$
11
$\begingroup$

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}}}*)
$\endgroup$
3
  • 2
    $\begingroup$ 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 $\endgroup$ Commented Dec 26, 2023 at 23:37
  • 2
    $\begingroup$ Use Infinity instead of 2 $\endgroup$ Commented Dec 26, 2023 at 23:46
  • $\begingroup$ @AndreasLauschke You're right, thanks for the suggestion. :-) $\endgroup$ Commented Dec 26, 2023 at 23:49
8
$\begingroup$
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}}}

$\endgroup$
6
$\begingroup$
list //. {} -> Sequence[]

and

list //. {} :> Unevaluated[## &[]]

both give

{{{1}, {2}, {1, 2}, {1, 2, 3}}, {{2}, {3}}}

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

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.