# Delete elements from nested list

I have a list with the following structure

list={ {x,y},{ {a1,b1},{a2,b3} } }


where the number of pairs {ai,bi} can be different. I would like to remove pairs {x,y} with y<0 and try to use

DeleteCases[list,{{_,b_},{__List}}/;b<0]


but this returns all elements of the list. What do I wrong?

Update: I have understood why my attempt is wrong but still do not understand how to remove these elements.

• For the DeleteCases approach, I recommend using the level argument. e.g. DeleteCases[list, {_, b_} /; b < 0, Infinity] Jun 11, 2020 at 10:09
• but you can't do b<0 on symbol. Jun 11, 2020 at 10:38
• Are you removing the entire entry in the list if conditions are satisfied or just the {x,y} pair? Jun 11, 2020 at 12:19
• Artem, your initial DeleteCases method does work, perhaps your list structure used for this is not like how I define lst in my answer? Jun 11, 2020 at 21:07

We can use a modification of the answer here to do this.

lst = {{{x1, -1}, {{a1, 1}, {c1, d1}}},
{{x2, 1 }, {{a2, -1}, {c2, d2}}},
{{x3, -1}, {{a3, 1}, {c3, d3}}},
{{x4, 1}, {{a4, -1}, {c4, d4}}}};

Extract[List@*First/@Position[a_/;a>=0][First/@lst]][lst]

{{{x2,1},{{a2,-1},{c2,d2}}},{{x4,1},{{a4,-1},{c4,d4}}}}


Or

Cases[{{x_,y_},{a__List}}:>{{x,y},{a}}/;y>=0][lst]


Same output.

If you need to only remove the {x,y} pair, I would need to think about that.

lst/.{{a_,b_?Negative},{c__List}}:>{{c}}

{{{{a1,1},{c1,d1}}},{{x2,1},{{a2,-1},{c2,d2}}},{{{a3,1},{c3,d3}}},{{x4,1},{{a4,-1},{c4,d4}}}}


This way loses the ordering, but it works with Cases and shows a terrible way to pseudo-use multiple conditions:

Cases[{{x_,y_},{a__List}}:>Evaluate@#]&/@{Unevaluated[{{x,y},{a}}/;y>=0],Unevaluated[{{a}}/;y<0]}//#[lst]&/@#&

{{{{x2,1},{{a2,-1},{c2,d2}}},{{x4,1},{{a4,-1},{c4,d4}}}},{{{{a1,1},{c1,d1}}},{{{a3,1},{c3,d3}}}}}

list/.{_,_?Negative}:>Nothing

• I think this will remove pairs of {a,b} that satisfy the condition also. Jun 11, 2020 at 12:17
• This way works if you use {{_,_?NegativeQ},{__List}}. Jun 11, 2020 at 14:50
• The biggest problem for this answer to be valid is, that this question has Cases[list, _?NumberQ] is empty {}! So it can not be jugded by Mathematica this way meaningful. This correctly recognized by @CATrevillian! Otherwise this asked for an example from the Mathematica documentation: [reference.wolfram.com/language/ref/PatternTest.html] section Scope example 1: replace negative numbers with 0 or something or Nothing. From [reference.wolfram.com/language/ref/Nothing.html] section Properties and Relation are other concepts available. Jun 12, 2020 at 9:04