# How to iterate through a lists of lists and delete a certain element?

Say I have a list of lists such as

l1 = {{a, 2}, {a, 5}, {b, 3}, {b, 9}}


How would I iterate through the list and delete all the lists with the first element b so that i can get

l2 = {{a,2}, {a, 5}}

• Welcome to MSE. One way to do it l1 // Select[FreeQ[First@#, b] &] – Rohit Namjoshi Oct 29 at 22:00

Another way.

l2 = l1 /. {b, _} -> Nothing
(* {{a, 2}, {a, 5}} *}

l1 = {{a, 2}, {a, 5}, {b, 3}, {b, 9}};
l2 = {{a, 2}, {a, 5}};
(*method 1*) DeleteCases[l1, {b, _}]
(*method 2*) Select[l1, First@#1 =!= b &];
(*method 3*) Select[l1, FreeQ[#, b] &];
(*method 4*) Pick[l1, #1 =!= b & @@@ l1];
(*method 5*) (l1 /. {b, _} -> Sequence[]);
(*method 6*) Reap[If[#[] =!= b, Sow@#, Sequence[]] & /@ l1][[2, 1]];
SameQ @@ Out[-Range]


{{a, 2}, {a, 5}}

True

And a more procedural way/actually using iterators, and "deleting" the "b"s instead of picking out the not-"b"s,

Block[
{list = l1, i = 0},
Do[
If[l1[[k, 1]] === b, list = Delete[list, k - i]; i++],
{k, Length@l1}
];
list
]


{{a, 2}, {a, 5}}