6
$\begingroup$

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

$\endgroup$
  • $\begingroup$ Look at Drop[...] $\endgroup$ – QuantumPenguin Feb 18 '18 at 23:12
  • 1
    $\begingroup$ 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. $\endgroup$ – Kenneth Eaves Feb 18 '18 at 23:18
  • $\begingroup$ I'll use Position with Drop, just found that. Thank you $\endgroup$ – Kenneth Eaves Feb 18 '18 at 23:25
  • 1
    $\begingroup$ At least closely related: 18100, if at the end you want to delete multiple entries at once then this is a duplicate. $\endgroup$ – Kuba Feb 19 '18 at 7:06
9
$\begingroup$

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}

$\endgroup$
3
$\begingroup$

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}

$\endgroup$
3
$\begingroup$

Offered for brevity and style:

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

Tests:

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

drop[5] /@ {{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]
$\endgroup$
2
$\begingroup$
DeleteCases[list, y, 1, 1]

{3, 5, 5}

where

list = {3, 5, 5, 5};
y = 5;
$\endgroup$
1
$\begingroup$
drop[x_][list_] := ReplacePart[list, FirstPosition[list, x] :> Sequence[]]
$\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.