# Delete one item in a list

I have a list of 4 elements {a, b, c, d}.

One of the elements has been assigned to a variable, say y, at some point in the program.

I am looking for a command that will delete the element of the list that is the same as y, BUT if two, three, or four of the elements are the same as y, I only want to delete one of the elements that are the same.

For example, say y=2 and list={1, 2, 4, 6}. I want the new list to be {1, 4, 6}.

For another example, say y=5 and list={3, 5, 5, 5}. I want the new list to be {3, 5, 5}.

• Look at Drop[...] – Q.P. Feb 18 '18 at 23:12
• The problem I was having with Drop is that I don't know which element (1st, 2nd, 3rd, or 4th) y will end up being. – Kenneth Eaves Feb 18 '18 at 23:18
• I'll use Position with Drop, just found that. Thank you – Kenneth Eaves Feb 18 '18 at 23:25
• At least closely related: 18100, if at the end you want to delete multiple entries at once then this is a duplicate. – Kuba Feb 19 '18 at 7:06

How about FirstPosition:

y = 2;
list = {1, 2, 4, 6};
pos = FirstPosition[list, y]


{2}

Drop[list, pos]


{1, 4, 6}

and

y = 5;
list = {3, 5, 5, 5};
pos = FirstPosition[list, y]


{2}

Drop[list, pos]


{3, 5, 5}

Offered for brevity and style:

drop[x_][h_[a___, x_, b___]] := h[a, b]


Tests:

{1, 2, 4, 6} // drop

drop /@ {{3, 5, 5, 5}, {5, 2, 1, 5}}

foo[m, a, t, h, e, m, a, t, i, c, a] // drop[m] // drop[t]

{1, 4, 6}

{{3, 5, 5}, {2, 1, 5}}

foo[a, h, e, m, a, t, i, c, a]


This also works although, I think, less efficiently than corey979's method.

removeFirst[x_?NumericQ, nums : {_?NumericQ ..}] :=
Drop[nums, Catch[MapIndexed[If[#1 == x, Throw[#2], Nothing] &, nums]]]


### Test cases

removeFirst[2, {1, 2, 4, 6}]


{1, 4, 6}

removeFirst[5, {3, 5, 5, 5}]


{3, 5, 5}

When 1st argument is not found in 2nd argument, returns 2nd argument.

removeFirst[2, {3, 4, 5, 6}]


{3, 4, 5, 6}

Handles case where 1st argument is integer and 2nd is list of reals.

removeFirst[2, Range[1., 3., .5]]


{1., 1.5, 2.5, 3.}

Handles symbolic numbers.

removeFirst[Pi, {E, Pi, E, Pi}]


{E, E, Pi}

DeleteCases[list, y, 1, 1]


{3, 5, 5}

where

list = {3, 5, 5, 5};
y = 5;

drop[x_][list_] := ReplacePart[list, FirstPosition[list, x] :> Sequence[]]