Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a nested list of the form

{{{{a, 0},{b, 1},{c, 2}}, {{d, 4},{e, 5},{f, 6}}} ... }

where the $...$ just means it goes on like that. On the innermost level, as you can see, I have pairs of the form {string, number}. All I want to do is to delete from this nested list the pairs whose number entry is 0.

For instance, in the above example, I want to delete only the pair {a, 0}.

I've spent the last two hours reading up on answers on this website and elsewhere on the internet, without managing to successfully apply them to this case. Most commands just return the empty list. I also find it very hard to understand the syntax of pretty much all of the list-related commands.

I should also say that I don't really care about the nested structure being preserved or about speed, since the list isn't too big.

Thank you for your time.

share|improve this question
list/.{_, 0} :> Sequence[] – Algohi Feb 23 at 1:08
@Algohi it works, thank you! – Guest Feb 23 at 1:10
DeleteCases[list, {_, 0}, ∞] also works. – bbgodfrey Feb 23 at 1:23
@bbgodfrey This DeleteCases command is the first that actually makes sense to me, so thank you very much. – Guest Feb 23 at 3:39
Also Select[#[[-1]] != 0 &][Partition[Flatten[list], 2]] - without nested structure and not fast :)) – garej Feb 23 at 10:59
up vote 4 down vote accepted

For the record, so that this question have answers in an Answer block, correct answers given in the comments to the OP include

  • list/.{_, 0} :> Sequence[]
  • DeleteCases[list, {_, 0}, ∞]

In addition, here are two that are similar to the ones above but slightly more specific to the requirements stated in the OP:

  • list/.{_, 0} -> Sequence[] (Rule instead of RuleDelayed)
  • DeleteCases[list, {_, 0}, {3}] (deletes only sublists at level 3)
share|improve this answer

Let's use a more complex expression than given above to stress the solution methods a bit more.

data = 
  {{{{a, 0}, {b, 1}, {c, 2}}, {{d, 4}, {e, 5}, {f, 6}}},
  {{{{{a, 0}}}, {b, 1}, {c, 2}}, {{d, 4}, {{e, 0}, {f, 6}}}}};

I think the following have advantages over the solutions already given.

data /. {_, 0} -> Nothing
DeleteCases[data, {_, 0}, {-2}]

Both give

{{{{b, 1}, {c, 2}}, {{d, 4}, {e, 5}, {f, 6}}}, 
 {{{{}}, {b, 1}, {c, 2}}, {{d, 4}, {{f, 6}}}}}

The first method I think more easily understood than /. {_, 0} :> Sequence[] and second simply is more robust -- DeleteCases[data, {_, 0}, {3}] fails on this more complex data list.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.