# Cases for nested lists

I have a nested list where each element looks like

{{x, y}, {{a, b}, {c, d}}}


I would like to extract elements of a list with $$b < 0$$, so I look for structure

{{x1, y1}, {{a1, b1}, {c1, d1}}},
{x1, y1}, {{a1, b1}, {c1, d1}}},
...}


First I try

Cases[list, {A_, B_} /; B < 0, 3]


but this gives undesired results:

{{x1, y1}, {a1, b1}, {x2, y2}, {a2, b3}, ...}


so original structure of list disappears and I have. Then I try

Cases[list, {A_, B_} /; B < 0, {3}]


and obtain a list of pairs

{{a1, b1}, {a2, b2}, ...}


What should I do to obtain the desired results?

The second question is how to deal with list with the following structure:

{ {{x1,y1},{{a1,-1},{a2,b2},{a3,b3}}}, {{x2,y2},{{a4,-1},{a5,b4}}} }


I mean that a number of pairs {ai,bi} in the second ''part'' of element can be different for each element.

Not to take away from kglr’s wonderful answer, but using their defined example lst, we can arrange a slightly more general application of Cases:

Cases[a_:>a/;a[[2,1,2]]<0][lst]


Same output as kglr.

In this way, it is somewhat an amalgam of the methods shown by kglr. You’ll need to know the position of your value in advance, of course, and you can then designate the desired conditions.

What if you don’t know the position of the values that you want to satisfy the condition?

Try this:

Extract[List@*First/@Position[a_/;a<0][Last/@lst]][lst]


Same output.

• @ArtemAlexandrov I updated the answer incase you might not know where in that list of unspecified length your condition satisfying value will be hiding! – CA Trevillian Jun 9 '20 at 15:33
lst = {{{x1, y1}, {{a1, 1}, {c1, d1}}},
{{x2,  y2}, {{a2, -1}, {c2, d2}}},
{{x3, y3}, {{a3, 1}, {c3, d3}}},
{{x4, y4}, {{a4, -1}, {c4, d4}}}};

Cases[{_, {{_, _?Negative}, __List}}] @ lst

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

Select[#[[2, 1, 2]] < 0 &] @ lst

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

Pick [lst, Negative[lst[[All, 2, 1, 2]]]]

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

• Like a magic! Thank you!!! – Artem Alexandrov Jun 9 '20 at 13:29
• What about if the element of the original list is {{x,y},{{a,b},{c,d}...}, i.e. the element consits of a pair {x,y} and list of a number of pairs {a,b}? (I have updated the question) – Artem Alexandrov Jun 9 '20 at 15:13
• @ArtemAlexandrov I think I unintentionally answered this :) – CA Trevillian Jun 9 '20 at 15:19
• @CATrevillian yes, thank you! – Artem Alexandrov Jun 9 '20 at 15:20
• @ArtemAlexandrov, just change _List to __List in Cases[....]. – kglr Jun 9 '20 at 18:21