4
$\begingroup$

I have the list

L=8;
indx = Range[-π, π, 2 π/L]
(* {-π, -((3 π)/4), -(π/2), -(π/4), 0, π/4, π/2, (3 π)/4, π} *)

Now I want to delete specific elements of this list, e.g -(π/2), 0, (3 π)/4

I make a new list which includes the values I wish to delete, i.e:

exvals={-(π/2), 0,  (3 π)/4};

and

For[i = 1, i <= Length[exvals], i++, indx = DeleteCases[indx, exvals[[i]]]]
indx
(*={-π, -(π/2), -(π/4), π/4, (3 π)/4, π} *)

which works fine. I am wondering if there is a more compact way to do it without using For

$\endgroup$
4
  • 2
    $\begingroup$ DeleteCases[indx, exvals] (should not change sorting order) or Complement[indx, exvals] (will return sorted list). $\endgroup$
    – MarcoB
    Jan 3, 2021 at 19:11
  • 1
    $\begingroup$ also DeleteCases[Alternatives @@ exvals]@indx. $\endgroup$
    – kglr
    Jan 3, 2021 at 19:14
  • $\begingroup$ Thanks @MarcoB. I was not aware of Complement. Please post it as a reply $\endgroup$
    – geom
    Jan 3, 2021 at 19:15
  • $\begingroup$ @kglr Thanks. Your suggestion also works fine. $\endgroup$
    – geom
    Jan 3, 2021 at 19:17

3 Answers 3

4
$\begingroup$

Two ways come to mind, which have different consequences on the ordering of the results. To show that, let me create a scrambled version of your list, so it is not ordered in numerical value:

L = 8;
indx = Range[-π, π, 2 π/L];

SeedRandom[20210103]
scrambled = RandomSample[indx]

(*Out: {π, π/2, -((3 π)/4), -(π/2), (3 π)/4, -π, -(π/4), π/4, 0} *)

You can then use DeleteCases or Complement to achieve functionally similar results, but with or without sorting the output, respectively:

DeleteCases[scrambled, Alternatives @@ exvals]
(* Out: {π, π/2, -((3 π)/4), -π, -(π/4), π/4} *)

Complement[scrambled, exvals]
(* Out: {-π, -((3 π)/4), -(π/4), π/4, π/2, π} *)
$\endgroup$
1
  • $\begingroup$ I should probably also mention the implementation of unsortedComplement[] here. $\endgroup$ Jan 4, 2021 at 4:50
2
$\begingroup$
list = Range[10];

del = {3, 7, 8};

1.

Using DeleteElements (new in 13.1)

DeleteElements[list, del]

{1, 2, 4, 5, 6, 9, 10}

Unlike Complement DeleteElements doesn't sort

DeleteElements[Reverse @ list, del]

{10, 9, 6, 5, 4, 2, 1}

2.

Using ReplaceAt (new in 13.1)

p = Position[list, Alternatives @@ del]

{{3}, {7}, {8}}

ReplaceAt[_ :> Nothing, p] @ list

{1, 2, 4, 5, 6, 9, 10}

$\endgroup$
1
$\begingroup$
list = Range[10];

del = {3, 7, 8};

Grabbing the @eldo's list and using MapAt:

MapAt[Nothing, #, Position[#, Alternatives @@ del]] &@list

(*{1, 2, 4, 5, 6, 9, 10}*)

Or using SubsetMap:

p = Position[list, Alternatives @@ del];

f = Array[Inactive[Nothing] &, Length@p];

Activate@SubsetMap[f &, list, p]

(*{1, 2, 4, 5, 6, 9, 10}*)
$\endgroup$

Your Answer

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

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