# How to use Cases to delete specific lists from a nested list

To simplify things, let's say that I have a list:

aList = {{1,2,3,4},{2,2,6,6},{6,9,8,7},{6,6,6,3}}


and I want to use Cases to get rid of the lists that have two or more 6's. So the output would be:

{{1,2,3,4},{6,9,8,7}}


I was only able to make this:

Cases[aList,x_/;Table[Count[aList[[i]],6]>=2,{i,1,Length[aList]}][[FromDigits[Flatten[Position[aList,x]]]]]!=True


but it seems... not simple, and it doesn't work with longer lists. Any suggestions?

• DeleteCases[aList, x_ /; Count[x, 6] > 2] or alternatively Cases[aList, x_ /; Count[x, 6] <= 2] or alternatively Select[aList, Count[#, 6] <= 2 &] Commented Aug 26, 2020 at 20:56
• Or, using Pick: aList//Pick[#,UnitStep[Count[#, 6]&/@#-2],0]& Commented Aug 26, 2020 at 21:04
• also DeleteCases[{___, 6, ___, 6, ___}]@aList and Cases[Except[{___, 6, ___, 6, ___}]]@aList
– kglr
Commented Aug 27, 2020 at 0:15

list = {{1, 2, 3, 4}, {2, 2, 6, 6}, {6, 9, 8, 7}, {6, 6, 6, 3}};


Using Replace and Count:

Replace[list, x_ /; ! Count[x, 6] < 2 :> Nothing, {1}]

(*{{1, 2, 3, 4}, {6, 9, 8, 7}}*)


Or using DeleteCases:

DeleteCases[list, {OrderlessPatternSequence[__, Repeated[6, {2, ∞}]]}]

(*{{1, 2, 3, 4}, {6, 9, 8, 7}}*)


Or using ReplaceList:

ReplaceList[list, {___, x : {b__ /; Count[{b}, 6] < 2}, ___} :> x]

(*{{1, 2, 3, 4}, {6, 9, 8, 7}}*)


Or using DeleteCases and Count:

DeleteCases[list, {b__ /; Count[{b}, 6] >= 2}]

(*{{1, 2, 3, 4}, {6, 9, 8, 7}}*)

list = {{1, 2, 3, 4}, {2, 2, 6, 6}, {6, 9, 8, 7}, {6, 6, 6, 3}};

DeleteCases[list, {OrderlessPatternSequence[6, 6, __]}]


{{1, 2, 3, 4}, {6, 9, 8, 7}}

Catenate @ SequenceSplit[list, {{OrderlessPatternSequence[6, 6, __]}}]


{{1, 2, 3, 4}, {6, 9, 8, 7}}

Extract[list, Position[Position[6] /@ list, {} | {{_}}]]


{{1, 2, 3, 4}, {6, 9, 8, 7}}

• Also: DeleteCases[list, {___, OrderlessPatternSequence[6, 6], ___}]
– Syed
Commented Feb 24 at 1:21
list = {{1, 2, 3, 4}, {2, 2, 6, 6}, {6, 9, 8, 7}, {6, 6, 6, 3}};


Using Pick with RightComposition

Pick[list, Count[6] /* LessThan[2] /@ list]


{{1, 2, 3, 4}, {6, 9, 8, 7}}

aList = {{1,2,3,4},{2,2,6,6},{6,9,8,7},{6,6,6,3}}
Select[aList, Length[Cases[#, 6]] < 2 &]

{{1, 2, 3, 4}, {6, 9, 8, 7}}