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.


2 Answers 2


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:


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:


Same output.

  • $\begingroup$ @ArtemAlexandrov I updated the answer incase you might not know where in that list of unspecified length your condition satisfying value will be hiding! $\endgroup$ Commented Jun 9, 2020 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}}}}
  • $\begingroup$ Like a magic! Thank you!!! $\endgroup$ Commented Jun 9, 2020 at 13:29
  • $\begingroup$ 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) $\endgroup$ Commented Jun 9, 2020 at 15:13
  • $\begingroup$ @ArtemAlexandrov I think I unintentionally answered this :) $\endgroup$ Commented Jun 9, 2020 at 15:19
  • $\begingroup$ @CATrevillian yes, thank you! $\endgroup$ Commented Jun 9, 2020 at 15:20
  • 2
    $\begingroup$ @ArtemAlexandrov, just change _List to __List in Cases[....]. $\endgroup$
    – kglr
    Commented Jun 9, 2020 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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