2
$\begingroup$

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}}
$\endgroup$
  • 1
    $\begingroup$ Welcome to MSE. One way to do it l1 // Select[FreeQ[First@#, b] &] $\endgroup$ – Rohit Namjoshi Oct 29 at 22:00
3
$\begingroup$

Another way.

l2 = l1 /. {b, _} -> Nothing
(* {{a, 2}, {a, 5}} *}
$\endgroup$
3
$\begingroup$
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[#[[1]] =!= b, Sow@#, Sequence[]] & /@ l1][[2, 1]];
SameQ @@ Out[-Range[6]]

{{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}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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