4
$\begingroup$

How to delete just first occurrence of given value from a list?
Without sorting etc.
Something like this:

DeleteFirstCase[{1/3, 1/2, 3/4, 1/2, 1/2, 1/2}, 1/2] -> {1/3, 3/4, 1/2, 1/2, 1/2}

Only

arr = {1/3, 1/2, 3/4, 1/2, 1/2, 1/2};
item = 1/2;
arr = Delete[arr, First@Position[arr, item]];

?

$\endgroup$
1
  • 1
    $\begingroup$ See the 3rd paradigm of the output of ?DeleteCases. $\endgroup$
    – Michael E2
    Feb 21 at 19:22

3 Answers 3

6
$\begingroup$
arr = {1/3, 1/2, 3/4, 1/2, 1/2, 1/2}
item = 1/2
FixedPointList[DeleteCases[#, item, {1}, 1] &, arr] // Grid

enter image description here

$\endgroup$
1
  • 4
    $\begingroup$ Yes, DeleteCases[arr, item, {1}, 1] $\endgroup$
    – lesobrod
    Feb 21 at 17:05
4
$\begingroup$

Using DeleteElements:

DeleteElements[{1/3, 1/2, 3/4, 1/2, 1/2, 1/2}, 1 -> {1/2}]

(*{1/3, 3/4, 1/2, 1/2, 1/2}*)

For 12.1 version, you can use SubsetReplace:

SubsetReplace[{1/3, 1/2, 3/4, 1/2, 1/2, 1/2}, {1/2} -> Nothing, 1]
 (*{1/3, 3/4, 1/2, 1/2, 1/2}*)

Your DeleteFirstCase using PositionIndex and KeyTake:

 DeleteFirstCase[l_List, item_] := 
 Module[{rules}, 
  rules = Flatten[
    Thread /@ (If[#[[2]] === item, 
         Rest[#[[1]]] -> #[[2]], #] & /@ (Reverse /@ 
         Normal@PositionIndex[l]))];
  (Join @@ Normal[KeyTake[rules, #] & /@ Range[Length[l]]])[[All, 2]]]

Test:

DeleteFirstCase[arr, item]
(*{1/3, 3/4, 1/2, 1/2, 1/2}*)

Using DeteleFirstCase with FixedPointList:

FixedPointList[DeleteFirstCase[#, item] &, arr] // Grid

enter image description here

$\endgroup$
1
  • $\begingroup$ Well, it's just from 13.1 Thank you, but i need something with backward compatibility for version 12 and under, for some reasons $\endgroup$
    – lesobrod
    Feb 21 at 16:50
2
$\begingroup$
lst//Drop[#,FirstPosition[#,1/2]]&

$$\left\{\frac{1}{3},\frac{3}{4},\frac{1}{2},\frac{1}{2},\frac{1}{2}\right\}$$

$\endgroup$

Your Answer

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

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