4

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

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
geom
  • 668
  • 3
  • 13

3 Answers3

4

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, π} *)

MarcoB
  • 67,153
  • 18
  • 91
  • 189
2
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}

eldo
  • 67,911
  • 5
  • 60
  • 168
1
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})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44