# Delete first case

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]];


?

• See the 3rd paradigm of the output of ?DeleteCases. Feb 21 at 19:22

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


• Yes, DeleteCases[arr, item, {1}, 1] Feb 21 at 17:05

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[
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


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


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