# How to use Cases for nested list?

For example, we have a list ={1,2,3,4,5,6}, we can use Cases[list,x_/; 3<x<10] to pick up {4,5,6}.

What if we are dealing with a nested list for example : list2={{0.1,0.2},{0.1,0.2},{0.2,0.3},{0.3,0.4}};

Shall I use something like Cases[list2,{x_,y_}/;0<x+y<0.5] to pick up {0.1,0.2}in this case?

• yes - but in both of your examples Select seems more natural than Cases – Jason B. Aug 18 '17 at 22:20
• I tried to build a complex nested list using this method, but get empty result that's why I ask this – leon365 Aug 18 '17 at 22:24
• First you have to make sure that your pattern matches the elements that you are trying to get. If it does, then you need to make sure that you are looking at the right level of your list. By default, Cases will match only at the top level: Cases[{{1},{2},{3}}, _Integer] will return {} because the elements at the top level would match {_Integer}. Cases[{{1}, {2}, {3}}, _Integer, 2], however, returns {1,2,3}. Look at the documentation for Cases, and look at the third argument in particular. – Jason B. Aug 18 '17 at 22:29
• Thank you very much sir! – leon365 Aug 19 '17 at 15:38

As @JasonB. mentions in the comments Select is an alternative that some say reads better.

Select[0 < Total@# < .5 &]@list2

{{0.1,0.2},{0.1,0.2}}


Hope this helps.

• Thanks for the help! – leon365 Aug 19 '17 at 15:37

You have answered your own question where you posted the question. Alternatively,

Cases[list2, x_ /; Plus @@ x < 0.5]

• Total @ might be more natural than Plus @@ – b3m2a1 Aug 19 '17 at 0:17

Yes looks correct, or you can put conditions on each one of the variables separated like that

Cases[list2, {x_, y_} /; x < 0.2 && y < 0.3]


If you have a nested list with elements of varying lengths:

list = {{0.1, 0.2, 0.0}, {{0.1, 0.2}}, {0.2, 0.3}, {0.3, 0.4}};

Cases[list, p : {__?NumericQ} /; Total@p < 0.5, -1]


{{0.1, 0.2, 0.}, {0.1, 0.2}}

• Thanks for the supplement! – leon365 Aug 19 '17 at 23:19